Chapter 6. Integration with Maven

The SonargraphBuild Maven plugin makes it easy to check the quality of your projects. The plugin is able to automatically download and install SonargraphBuild if your build server has Internet connectivity. You can make the build fail depending on issues detected by SonargraphBuild.

There are two different goals available:

  1. create-report: Creates a report for an existing system.

  2. dynamic-report: Creates a system on-the-fly and creates a report for it. This is currently only available for Java systems.

  3. help: Displays information about the other two goals and can be parameterized to show more details.

Prerequisites:

  1. You need at least Maven 3.0.5 installed.

  2. The plugin requires at least a Java 8 runtime.

  3. The plugin cannot be used together with Tycho.

6.1. Maven Tips and Best Practices

TIP

Add the following repository to your Maven settings.xml, so you do not need to repeat it in your project's pom.xml:

<pluginRepository>
    <id>hello2morrow.maven.repository</id>
    <url>http://maven.hello2morrow.com/repository</url>
</pluginRepository>

TIP

The goals are not configured to be executed within any default Maven lifecycle phase. Typically you would run the plugin with a command-line like the following to ensure that everything is compiled from scratch before the report is created. The first command-line explicitly specifies a version, the second one uses the Maven prefix resolution (check Maven Prefix Resolution for details):

mvn clean compile com.hello2morrow:sonargraph-maven-plugin:9.4.4:create-report

mvn clean compile sonargraph:create-report

TIP

All parameters of the top-level goals (i.e. not the failSet) can equally be set via the command-line using system properties of the form

-Dsonargraph.<parameter-name>=<value>

TIP

To enforce certain rules, specify a failSet that lets the build fail based on detected issues. See Section 6.4, “Maven FailSet Configuration”

NOTE

The plugin cannot be used together with Tycho.

You need to use another option to execute Sonargraph. See Chapter 4, Executing from the Command-line, Chapter 5, Integrating with Ant. If the class root paths of the Sonargraph workspace do not match the Maven target directories, check the section about "Workspace Profiles" in the user manual of the standalone application: http://eclipse.hello2morrow.com/doc/standalone/content/workspace_profiles.html

NOTE

The attribute "logLevel" affects the logging after the SonargraphBuild engine has been started. Setting it to "debug" and below will generate additional debug information into the XML report.

WARNING

Setting the attribute "reportType" to "standard" only generates metric values for "system" and "module" levels. "full" generates values for all element levels, but results in a significant larger report!

The splitting of the HTML report into different files is controlled by the attribute "elementCountToSplit​HtmlReport". The resulting detail pages contain tables of issues / resolutions of a specific issue type. The maximum number of items shown is limited by the parameter "maxElementCountFor​HtmlDetailsPage".

WARNING

The attribute "qualityModelFile" can be used to apply a fixed set of scripts, architecture files and analyzer configurations across several systems.

The reported issues are most likely very different from the results of analyzing the system with the Sonargraph application. If you specify a "qualityModelFile", it is advisable to specify the "Parser" virtual model, since resolutions e.g. for architecture violations probably will not match.

6.2. Parameters of Goal "create-report"

The following table lists all parameters that are available to create a report for an existing Sonargraph system. The class root directories are replaced by the output directories known to Maven.

NOTE

If Maven generates additional output directories dynamically that must be part of the Sonargraph workspace, the Sonargraph plugin must be executed within the same process as the plugins that generate the additional directories.

The build can be marked as failed based on a failSet. See Section 6.4, “Maven FailSet Configuration”.

Attribute Mandatory Description Default
sonargraphBuildVersion No Allows you to use a specific or restricted version of SonargraphBuild. Can be used in combination with 'autoUpdate'. As an example, if you specify '8.7' the newest available version starting with '8.7' will be used. If you specify '8.7.0.361' you are locked on that specific version of SonargraphBuild. There are two special values: "same" and "newest". If "same" is defined the version of SonargraphBuild must be the same as the version of the Maven plugin. If "newest" is defined the plugin will always try to use the newest version of SonargraphBuild. same
skip No Skip SonargraphBuild. false
autoUpdate No If the plugin is configured to download SonargraphBuild automatically, this parameter decides if it also should be updated automatically if a new version becomes available. false
useHttpProxyHost No The id of a proxy entry in the Maven settings. If defined the plugin will use this proxy for all HTTP communication. No default
installationDirectory No Installation directory of SonargraphBuild. If unspecified the plugin will automatically download SonargraphBuild. The version to be downloaded can be controlled by the parameter 'sonargraphBuildVersion'. No default
activationCode No Sonargraph license activation code. If this parameter is not specified, you must specify a license file parameter (see below). No default
licenseServerPort No Port of license server to be used. This parameter is ignored if licenseServerHost is not set. 8080
licenseServerHost No Host name or IP address of license server. If this parameter is not specified, the web-based hello2morrow license server will be used for activation code based licenses. No default
licenseFile No Sonargraph license file location. If this parameter is not specified, you must specify the activation code parameter (see above). No default
languages No The languages that should be initialized, separated by ",". The fewer languages are specified the faster the startup of SonargraphBuild. Possible values: Java, CSharp, CPlusPlus. Java
logFile No Path of the log file to be used for SonargraphBuild. ${baseDir}/${target}/sonargraph_build.log
logLevel No Level of logging detail. One of: off, error, warn, info, debug, trace, all info
compilerDefinitionPath No

The path to the active compiler definition file to be used for parsing a C/C++ system. If a built-in or automatically generated definition should be used, prefix the definition with "CPlusPlus:", e.g. CPlusPlus:GnuCpp.cdef.

NOTE: If the standalone Sonargraph application is used on the same machine with the same user and this parameter is empty, the active definition specified with the standalone application will be used.

If empty, the default compiler definition for the build server's operating system is used: GnuCpp.cdef (Linux), CLang.cdef (Mac), VisualCpp*.cdef (Windows, generated definition for the latest Visual Studio installation)
systemDirectory No Directory of the Sonargraph System (xyz.sonargraph) ${baseDir}/${artifact.id}.sonargraph
overrideSonargraphWorkspace No If true the output directories defined in the Sonargraph system will be overridden by the ones provided by the client. true
includeTestCode No If true the workspace will also contain the test source and test class file directories. false
includeEmptyModules No If true the workspace will also contain empty modules (without any source and class file directories). false
virtualModel No The virtual model to be used when checking for issues. This parameter overrides the default virtual model that is set when the system is opened. The default virtual model is "Modifiable.vm", if virtual models are licensed, "Parser" if not licensed. Parameter can only be used with Sonargraph Architect license. No default
qualityModelFile No The path to the quality model file (xyz.sgqm) that should be applied for the report creation. Built-in quality models are the language-independent "Sonargraph:Default.sgqm" and language-specific "Sonargraph:Java.sgqm", "Sonargraph:CSharp.sgqm" and "Sonargraph:CPlusPlus.sgqm". NOTE: All scripts, analyzer configurations and architecture files present in the system are ignored! No default
snapshotDirectory No Target directory for the created snapshot. Only if either this parameter or snapshotFileName is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. ${basedir}/${target}
snapshotFileName No The target file name (without extension). Only if either this parameter or snapshotDirectory is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. <system-name>_<timestamp>
reportDirectory No Target directory for the created report ${basedir}/${target}/sonargraph
reportFileName No The target file name (without extension) <system-name>_<timestamp>
reportType No "standard" only creates metric information of system and module level. "full" creates metric information of all levels. standard
reportFormat No "xml", "html" or "xml, html" html

elementCountToSplit
HtmlReport

No Issue and resolution tables might contain too many items making it impossible to open the HTML report in a browser. This parameter controls the lower limit of items that will cause separate files being generated per issue type. Possible values are: -1 (never split), 0 (use default value), 1 (always split), positive number > 1 (threshold for split) 1000

maxElementCountFor
HtmlDetailsPage

No If HTML report is split because of too many issues and/or resolutions, detail tables might contain too many items making it impossible to open the page in a browser. This parameter controls the upper limit of elements shown in the table. Possible values are: -1 (no limit), 0 (use default limit), positive number > 1 (maximum number of elements contained in page) 2000
splitByModule No If set to 'true', individual HTML reports are created per module. false
baselineReportPath No Path of the baseline XML report that the current report is compared against No default
deltaReportPath No Path of the output file that the delta info is written to. This log file is only generated if a baselineReportPath has been specified. <reportDirectory>/<reportFileName>​_delta.log
prepareForSonarQube No Creates an XML report and stores it at ${basedir}/${target}/sonargraph/sonargraph-sonarqube-report.xml, where the SonarQube Sonargraph plugin expects it. false
Table 6.1. Configuration for goal "create-report"


Related topics:

6.3. Configuration for goal "dynamic-report"

The following table lists all parameters that are available to create a report for a Java project where no Sonargraph system has been defined. A Sonargraph system is created on the fly based on the workspace information contained in the Maven project setup.

NOTE

If your Maven build generates source and class roots dynamically, the "dynamic-report" goal should be called in the same process as those plugins that generate the additional roots. The following Maven execution also makes the dynamic roots available to Sonargraph:

mvn compile sonargraph:dynamic-report

Whereas using the following two separate Maven invocations, the dynamic roots will NOT be visible to Sonargraph:

mvn compile
mvn sonargraph:dynamic-report

The build can be marked as failed based on a failSet. See Section 6.4, “Maven FailSet Configuration”.

Attribute Mandatory Description Default
sonargraphBuildVersion No Allows you to use a specific or restricted version of SonargraphBuild. Can be used in combination with 'autoUpdate'. As an example, if you specify '8.7' the newest available version starting with '8.7' will be used. If you specify '8.7.0.361' you are locked on that specific version of SonargraphBuild. There are two special values: "same" and "newest". If "same" is defined the version of SonargraphBuild must be the same as the version of the Maven plugin. If "newest" is defined the plugin will always try to use the newest version of SonargraphBuild. same
skip No Skip SonargraphBuild. false
autoUpdate No If the plugin is configured to download SonargraphBuild automatically, this parameter decides if it also should be updated automatically if a new version becomes available. false
useHttpProxyHost No The id of a proxy entry in the Maven settings. If defined the plugin will use this proxy for all HTTP communication. No default
installationDirectory No Installation directory of SonargraphBuild. If unspecified the plugin will automatically download SonargraphBuild. The version to be downloaded can be controlled by the parameter 'sonargraphBuildVersion'. No default
activationCode No Sonargraph license activation code. If this parameter is not specified, you must specify a license file parameter (see below). No default
licenseServerPort No Port of license server to be used. This parameter is ignored if licenseServerHost is not set. 8080
licenseServerHost No Host name or IP address of license server. If this parameter is not specified, the web-based hello2morrow license server will be used for activation code based licenses. No default
licenseFile No Sonargraph license file location. If this parameter is not specified, you must specify the activation code parameter (see above). No default
languages No The languages that should be initialized, separated by ",". The fewer languages are specified the faster the startup of SonargraphBuild. Possible values: Java, CSharp, CPlusPlus. Java
logFile No Path of the log file to be used for SonargraphBuild. ${baseDir}/${target}/sonargraph_build.log
logLevel No Level of logging detail. One of: off, error, warn, info, debug, trace, all info
systemBaseDirectory No The directory where the Sonargraph System (${artifactId}.sonargraph) is created. ${baseDir}/${target}
systemId No A system id should stay constant over the lifetime of a software system and should be also unique with respect to other systems. If you anticipate that the the group id or artifact id of the root pom might change you should assign a value to this parameter. ${groupdId}_${artifactId}
useGroupIdInModuleName No If true the module names will use group id and artifact id as their name, separated by an underscore. By default only the artifact id is used as the module name. false
includeTestCode No If true the workspace will also contain the test source and test class file directories. false
includeEmptyModules No If true the workspace will also contain empty modules (without any source and class file directories). false
virtualModel No The virtual model to be used when checking for issues. This parameter overrides the default virtual model that is set when the system is opened. The default virtual model is "Modifiable.vm", if virtual models are licensed, "Parser" if not licensed. Parameter can only be used with Sonargraph Architect license. No default
qualityModelFile No The path to the quality model file (xyz.sgqm) that should be applied for the report creation. Built-in quality models are the language-independent "Sonargraph:Default.sgqm" and language-specific "Sonargraph:Java.sgqm", "Sonargraph:CSharp.sgqm" and "Sonargraph:CPlusPlus.sgqm". NOTE: All scripts, analyzer configurations and architecture files present in the system are ignored! No default
snapshotDirectory No Target directory for the created snapshot. Only if either this parameter or snapshotFileName is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. ${basedir}/${target}
snapshotFileName No The target file name (without extension). Only if either this parameter or snapshotDirectory is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. <system-name>_<timestamp>
reportDirectory No Target directory for the created report ${basedir}/${target}/sonargraph
reportFileName No The target file name (without extension) <system-name>_<timestamp>
reportType No "standard" only creates metric information of system and module level. "full" creates metric information of all levels. standard
reportFormat No "xml", "html" or "xml, html" html

elementCountToSplit
HtmlReport

No Issue and resolution tables might contain too many items making it impossible to open the HTML report in a browser. This parameter controls the lower limit of items that will cause separate files being generated per issue type. Possible values are: -1 (never split), 0 (use default value), 1 (always split), positive number > 1 (threshold for split) 1000

maxElementCountFor
HtmlDetailsPage

No If HTML report is split because of too many issues and/or resolutions, detail tables might contain too many items making it impossible to open the page in a browser. This parameter controls the upper limit of elements shown in the table. Possible values are: -1 (no limit), 0 (use default limit), positive number > 1 (maximum number of elements contained in page) 2000
splitByModule No If set to 'true', individual HTML reports are created per module. false
baselineReportPath No Path of the baseline XML report that the current report is compared against No default
deltaReportPath No Path of the output file that the delta info is written to. This log file is only generated if a baselineReportPath has been specified. <reportDirectory>/<reportFileName>​_delta.log
prepareForSonarQube No Creates an XML report and stores it at ${basedir}/${target}/sonargraph/sonargraph-sonarqube-report.xml, where the SonarQube Sonargraph plugin expects it. false
Table 6.2. Configuration for goal "dynamic-report"


Related topics:

6.4. Maven FailSet Configuration

The following elements allow to mark a build as failed. An example is shown in the next section Section 6.5, “Example POM”.

TIP

The issue type that must be specified for include/exclude definitions can be determined via the Properties View of Sonargraph .

TIP

If you want the build to fail only for newly introduced issues, apply resolutions like "Ignore" or "Fix" to the already know issues in Sonargraph and only filter for resolution value "none".

TIP

If you want the build to fail because of certain metric values (e.g. Lines of Code per Source File), define a threshold for that metric in Sonargraph to create issues if files grow too large.

TIP

The include/exclude definitions are applied in the following sequence, regardless of their definition order:

  1. First all include definitions are matched against the set of existing issues.

  2. Then the exclude definitions are applied and the set of previously matched issues is reduced accordingly.

Element Parameter Mandatory Description Default
failSet failOnEmptyWorkspace No Marks the build as failed if modules and root directories are detected but no components are found. Possible values are "true" or "false". true
include/exclude issueType Yes Name of the issue type or "any" for wildcard matching. No default
include/exclude severity No Severity of the issue. Possible values are: error, warning, info, none, any any
include/exclude resolution No The issue's resolution type. Possible values are: task, ignore, any, none none
Table 6.3. Configuration Parameters for Build Failure


6.5. Example POM

The following example shows how to integrate the Sonargraph Maven plugin into your project specific pom file. For multi-module projects it is sufficient to only add the plugin to the pom of the root project. It runs as an aggregator after all modules have been compiled. The example project in the installation contains a complete pom.xml. Typically you would run the plugin with a command-line like the following to ensure that everything is compiled from scratch before the report is created. The first command-line explicitly specifies a version, the second one uses the Maven prefix resolution (check Maven Prefix Resolution for details):

mvn clean compile com.hello2morrow:sonargraph-maven-plugin:9.4.4:create-report

mvn clean compile sonargraph:create-report

The following shows the relevant section of a pom.xml file that demonstrates the configuration of the Sonargraph functionality:

  <pluginRepositories>
    <pluginRepository>
        <id>hello2morrow.maven.repository</id>
        <url>http://maven.hello2morrow.com/repository</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <plugins>
        <plugin>
            <groupId>com.hello2morrow</groupId>
            <artifactId>sonargraph-maven-plugin</artifactId>
            <version>9.4.4</version>
            <configuration>
                <systemDirectory>${basedir}/crm-domain-example.sonargraph</systemDirectory>
                <activationCode>...</activationCode>
                <autoUpdate>true</autoUpdate>
                <failSet>
                    <failOnEmptyWorkspace>true</failOnEmptyWorkspace>
                    <includes>
                        <include>
                            <issueType>ArchitectureViolation</issueType>
                        </include>
                        <include>
                            <issueType>any</issueType>
                            <severity>error</severity>
                        </include>
                    </includes>
                    <excludes>
                        <exclude>
                            <issueType>ScriptCompilationError</issueType>
                            <resolution>none</resolution>
                        </exclude>
                    </excludes>
                </failSet>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>create-report</goal>
                        <goal>dynamic-report</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

In this example the build will fail if the project contains a package cycle or an architecture violation without a resolution. Since the parameter 'installationDirectory' is not defined, the Maven plugin will automatically download the newest release of SonargraphBuild and also will keep it updated automatically. Of course this requires that the build server has access to the Internet.