Integrating Travis, SonarQube and GitHub

The Travis configuration file

See the TL;DR for the whole code, here I will break each section down.

language: java
jdk:
  - oraclejdk8

Sets up the Java environment.  For SonarQube to work only oraclejdk8 is supported as there are no other JDK8 provided in Travis at the moment.

An alternate JDK can be used for builds and Sonar can still run on JDK 8, I will explain that later on.

sudo: false

Enables container based setting on Travis which is generally faster than their legacy builds.

cache:
  directories:
  - "$HOME/.m2/repository"
  - "$HOME/.sonar/cache"

Caches the downloaded files for later builds so they do not have to be downloaded again.

addons:
  sonarqube: 
    organization: organization-key
    token:
      secure: ...

Enables SonarQube add-on for Travis. A lot of magic happens there so we don’t have to do as much coding in .travis.yml. There are two required parameters one is `organization` where you need to pass in the organization key. Another option to pass the organization is to put it in the `pom.xml` via the property `sonar.organization`.

Secondly you need to pass in the SonarQube.com token which is added using

travis encrypt [sonarqube.com token] --add addons.sonarqube.token

The Travis CLI will add it to the proper place or create the section as needed.

install:
- mvn dependency:go-offline

As per the Travis guideline, the install phase is meant to get the dependencies loaded for the actual build execution. This is incorrectly done by the default Travis configuration, the dependency:go-offline goal is more appropriate as it downloads all the needed dependencies for the build to work.

script:
- mvn verify site sonar:sonar -Dmaven.test.failure.ignore=true

The meat of the build. This is where the package gets built and verified first and then SonarQube gets executed. The -Dmaven.test.failure.ignore=true ensures that Sonar will still run even though there are test failures, primarily if you have of legacy tests that are failing. Do not use `after_success` for `sonar:sonar` as it will not utilize the cache for the downloaded SonarQube plugin files.

Alternate JDK for build and scan

Let’s say the build requires an older version of the JDK. We just need to use jdk_switcher before the Sonar analysis.

jdk:
  - openjdk7
...
after_success:
  - jdk_switcher use oraclejdk8
  - mvn sonar:sonar