Run SonarScanner analysis with Java 11, run target code with Java 8

Viewed 4245

As the following image points out, SonarSource ended support to run code Analyzers with pre-11 Java versions

Sonar ending support for analysis with Java 8-9-10

I have tried to search for a full example about how to run a bitbucket pipeline to execute SonarScanner analysis using a java 11 Analyzer but having target code using pre-java 11 versions (e.g. java 8), but I wasn't able to found one. According to that image, it should be possible.

3 Answers

I'm not sure what is the problem. The announcements informs that you have to use Java 11+ to execute scans, but you can still compile your code with Java <11. You didn't provide any information about your project, so let's take a Maven project as an example.

It generally means that you have to do something like this:

// set Java to 8
export JAVA_HOME=/path/to/jdk8/

// compile, test and build
mvn package

// set Java to 11
export JAVA_HOME=/path/to/jdk11/

// execute scanner
mvn sonar:sonar

While @agabrys offers the most straightforward solution and the one we use, albeit via Jenkins freestyle job, invoke maven top-level target package, then end-inject JAVA_HOME variable and invoke maven sonar step, an alternative approach is ...

Use Java 11 throughout, but in your maven pom, specify:

<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

This is a minor risk of runtime incompatibility as noted at the bottom of that page.

Another alternative is to use profiles in conjunction with maven toolchains, tied to different profiles, one for the compilation and one for the analysis steps.

I faced the same issue in my project as well, where my project needed jdk8 to compile but SonarScan needed jdk11 and I was bound to use the sonar:sonar plugin for maven and NOT the direct sonarscanner binary.

To get around that, I used docker container, only to run the sonarscan part. Compilation part was still done with the host's maven itself.

To run the SonarScan using docker, use the command like below:

docker run -u $(id -u ${USER}):$(id -g ${USER}) --rm -v "$PWD":/usr/src/mymaven -v "$HOME/.m2":/tmp/.m2 -w /usr/src/mymaven maven:3-openjdk-11 \
         mvn -gs=/tmp/.m2/settings.xml -Dmaven.repo.local=/tmp/.m2/repository sonar:sonar \
        -Dsonar.dependencyCheck.jsonReportPath=target/dependency-check-report.json \
        -Dsonar.dependencyCheck.htmlReportPath=target/dependency-check-report.html \
        -Dsonar.dependencyCheck.summarize=true \
        -Dsonar.host.url=https://my-sonar-url \
        -Dsonar.login=****
Related