# Use SonarQube for Code Inspection

> [SonarQube](https://www.sonarqube.org/) is a great code inspection tool for code quality and code security. It provides Docker image for easy setup of the server, and Maven plugin for code inspection.

# Install and Setup SonarQube

1. [Install SonarQube from Docker image](https://docs.sonarqube.org/latest/setup/get-started-2-minutes/).
    
    ```shell
    docker run -d --name sonarqube \
    -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true \
    -p 9000:9000 sonarqube:latest
    ```
    
    * To restart:
        
    
    ```shell
    docker restart sonarqube
    ```
    
2. Once the instance is up and running, log in to http://localhost:9000 using System Administrator credentials:
    
    ```shell
    login: admin
    password: admin
    ```
    
    * Change password for first time login as requested.
        
3. Generate a token.
    
    i. From the menu at top right corner, click "My Account".
    
    ![SonarQube-MyAccount.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666254194709/Iq-zS3Hyt.png align="left")
    
    ii. Select the "Security" tab.
    
    ![SonarQube-GenerateToken.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666253797525/36sU_4bOG.png align="left")
    
    iii. In the "Tokens" section, enter Token Name and click the "Generate" button.
    
    ![SonarQube-TokenGenerated.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666254327734/dh_32JbiB.png align="left")
    

# Run code inspection using Maven plugin

1. Add Maven plugin in pom.xml.
    
    ```xml
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>3.9.1.2184</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    ```
    
2. Run analysis using the following command:
    
    ```shell
    export PROJECT_KEY=hello-world
    export SONAR_URL=http://localhost:9000
    export SONAR_TOKEN=74747088e1eb4cb74efd2495f351b5125214b74e
    
    mvn clean verify sonar:sonar \
        -Dsonar.projectKey=$PROJECT_KEY \
        -Dsonar.host.url=$SONAR_URL \
        -Dsonar.login=$SONAR_TOKEN
    ```
    
3. Check the result via the admin console.
    
    ![SonarQubeResults.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666256061068/T5MGL26gY.png align="left")
