Sonarqube is one recommended tools that we can leverage to do code quality scanning, and we can integrate it seamlessly with our Java build tool which is Maven. Having it integrated would make scanning easier since we can do it before build our application, while enforcing a quality gate to prevent low quality codes from going to the next phase.
Integrating Sonarqube to our application is actually quite simple, since a pom.xml configuration is sufficient enough for this. We can define all the required configurations on the “properties” tag,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.edw</groupId>
<artifactId>java-sonarqube</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- sonar -->
<sonar.language>java</sonar.language>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.coverage.jacoco.xmlReportPaths>${project.basedir}/target/site/jacoco/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
<sonar.jacoco.reportsPaths>${project.build.directory}/jacoco.exec</sonar.jacoco.reportsPaths>
<sonar.tests>src/test/java</sonar.tests>
<sonar.host.url>${SONAR_URL}</sonar.host.url>
<sonar.projectKey>${SONAR_PROJECT_KEY}</sonar.projectKey>
<sonar.projectName>${SONAR_PROJECT_NAME}</sonar.projectName>
<sonar.token>${SONAR_TOKEN}</sonar.token>
<sonar.scm.disabled>true</sonar.scm.disabled>
</properties>
</project>
and run it with below command,
$ mvn clean verify sonar:sonar \
-DSONAR_URL=http://xxxxx \
-DSONAR_PROJECT_KEY=xxxxx \
-DSONAR_PROJECT_NAME=xxxxx \
-DSONAR_TOKEN=xxxxx
A much more detail sample code can be found on below Github repository,
https://github.com/edwin/java-sonarqube