Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux SonarQube API 實戰:Java 程式碼取得違規數與程式碼行數完整範例

編輯:關於 Linux

SonarQube 是主流程式碼品質管理平台,提供 REST API 供外部系統整合。本文示範如何使用 Sonar Java Client 透過 API 取得專案的 違規數 與 程式碼行數,包含 Maven 依賴配置、完整程式碼範例與常見錯誤排查。

SonarQube 儀表板

一、Maven 依賴配置

<dependencies>
    <!-- SonarQube WS Client -->
    <dependency>
        <groupId>org.sonarsource.sonarqube</groupId>
        <artifactId>sonar-ws-client</artifactId>
        <version>8.9.0.52192</version> <!-- 對應 SonarQube 版本 -->
    </dependency>
    
    <!-- HTTP Client (Apache HttpClient 4) -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
    
    <!-- JSON 處理 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.3</version>
    </dependency>
</dependencies>

二、完整 Java 程式碼範例

import org.sonar.wsclient.Sonar;
import org.sonar.wsclient.HttpClient4Connector;
import org.sonar.wsclient.Host;
import org.sonar.wsclient.services.Resource;
import org.sonar.wsclient.services.ResourceQuery;
import org.sonar.wsclient.services.Measure;
import java.text.DecimalFormat;
import java.util.List;

public class SonarMetricsFetcher {
    
    // 設定區
    private static final String SONAR_HOST = "https://your-sonar-server:9000";
    private static final String USERNAME = "your_username";
    private static final String PASSWORD = "your_password";
    private static final String PROJECT_KEY = "com.example:my-project";
    
    // 要查詢的指標鍵
    private static final String[] METRICS = {
        "violations",      // 違規總數
        "lines",           // 程式碼總行數
        "ncloc",           // 非註解程式碼行數
        "classes",         // 類別數
        "functions",       // 函數數
        "complexity",      // 圈複雜度
        "comment_lines_density", // 註解密度
        "duplicated_lines_density" // 重複程式碼密度
    };
    
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("#.##");
        
        try {
            // 1. 建立 Sonar Client
            Host host = new Host(SONAR_HOST, USERNAME, PASSWORD);
            Sonar sonar = new Sonar(new HttpClient4Connector(host));
            
            // 2. 建立資源查詢
            ResourceQuery query = ResourceQuery.createForMetrics(PROJECT_KEY, METRICS);
            query.setIncludeTrends(true);  // 包含趨勢資料
            
            // 3. 執行查詢
            Resource resource = sonar.find(query);
            
            if (resource == null) {
                System.err.println("專案不存在或無權限: " + PROJECT_KEY);
                return;
            }
            
            // 4. 解析並輸出結果
            System.out.println("=== SonarQube 指標: " + PROJECT_KEY + " ===");
            List measures = resource.getMeasures();
            
            for (Measure measure : measures) {
                String key = measure.getMetricKey();
                double value = measure.getValue();
                String trend = measure.getTrend() != null ? " [" + measure.getTrend() + "]" : "";
                System.out.printf("%-35s: %s%s%n", key, df.format(value), trend);
            }
            
            // 5. 額外:取得歷史趨勢(若啟用 setIncludeTrends)
            // measure.getHistory() 可取得歷史資料點
            
        } catch (Exception e) {
            System.err.println("查詢失敗: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

三、關鍵 API 說明

四、常用指標鍵對照表

類別/方法用途
Sonar主要客戶端入口
HttpClient4ConnectorHTTP 連接器實作
Host(url, user, pass)伺服器連線資訊(支援 Token:new Host(url, token))
ResourceQuery.createForMetrics(key, metrics[])建立指定指標查詢
query.setIncludeTrends(true)包含趨勢資料
sonar.find(query)執行查詢,回傳 Resource
resource.getMeasures()取得所有指標測量值
measure.getMetricKey()指標鍵名
measure.getValue()數值(double)
measure.getTrend()趨勢:UP/DOWN/STABLE

五、進階:使用 SonarQube Web API 直接呼叫(無 Java Client)

# 直接 HTTP 呼叫(適合 Shell 腳本、Python、curl)
curl -u "username:password" \
  "https://sonar:9000/api/measures/component?componentKey=com.example:my-project&metricKeys=violations,lines,ncloc,coverage"

# 回傳 JSON 範例
{
  "component": {
    "key": "com.example:my-project",
    "measures": [
      {"metric": "violations", "value": "42", "bestValue": false},
      {"metric": "lines", "value": "15823", "bestValue": false},
      {"metric": "ncloc", "value": "12450", "bestValue": true},
      {"metric": "coverage", "value": "78.5", "bestValue": true}
    ]
  }
}

六、認證方式對比

指標鍵中文名稱說明
violations違規總數所有嚴重等級規則違規總和
blocker_violations阻斷級違規嚴重度 Blocker
critical_violations嚴重級違規嚴重度 Critical
major_violations主要違規嚴重度 Major
minor_violations次要違規嚴重度 Minor
info_violations資訊級違規嚴重度 Info
lines總行數含空行、註解
ncloc非註解行數NCLOC,實際程式碼行數
classes類別數
functions函數/方法數
complexity圈複雜度決策點總和
cognitive_complexity認知複雜度更貼近人類理解的複雜度
duplicated_lines_density重複程式碼密度百分比
coverage測試覆蓋率行覆蓋率 %
branch_coverage分支覆蓋率分支覆蓋率 %

建議:生產環境一律使用 Token,在 SonarQube UI → My Account → Security 產生。

七、常見錯誤與排查

方式適用場景安全性
Basic Auth (帳密)測試、內部腳本中(傳輸需 HTTPS)
User TokenCI/CD、生產整合高(可撤銷、有期限)
Application Token機器對機器高

整合 SonarQube API 能將程式碼品質指標納入 CI/CD 管線、自動化報表、品質閘門決策,是 DevOps 落地的關鍵環節之一。

Copyright © Windows教程網 All Rights Reserved
錯誤原因解決
401 Unauthorized帳密/Token 錯誤、權限不足確認憑證、專案權限(需 Browse 權限)
404 Not Found專案鍵錯誤、專案不存在確認 PROJECT_KEY 格式:group:artifact
SSLHandshakeExceptionHTTPS 憑證不信任匯入憑證或 -Djavax.net.ssl.trustStore
NoSuchMethodErrorWS Client 版本與 SonarQube 版本不符對齊版本號(參考官方相容性矩陣)
ConnectTimeout網路不通、防火牆檢查連線、Proxy 設定