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

一、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 | 主要客戶端入口 |
HttpClient4Connector | HTTP 連接器實作 |
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 |
四、常用指標鍵對照表
| 指標鍵 | 中文名稱 | 說明 |
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 | 分支覆蓋率 | 分支覆蓋率 % |
五、進階:使用 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}
]
}
}
六、認證方式對比
| 方式 | 適用場景 | 安全性 |
| Basic Auth (帳密) | 測試、內部腳本 | 中(傳輸需 HTTPS) |
| User Token | CI/CD、生產整合 | 高(可撤銷、有期限) |
| Application Token | 機器對機器 | 高 |
建議:生產環境一律使用 Token,在 SonarQube UI → My Account → Security 產生。
七、常見錯誤與排查
| 錯誤 | 原因 | 解決 |
| 401 Unauthorized | 帳密/Token 錯誤、權限不足 | 確認憑證、專案權限(需 Browse 權限) |
| 404 Not Found | 專案鍵錯誤、專案不存在 | 確認 PROJECT_KEY 格式:group:artifact |
| SSLHandshakeException | HTTPS 憑證不信任 | 匯入憑證或 -Djavax.net.ssl.trustStore |
| NoSuchMethodError | WS Client 版本與 SonarQube 版本不符 | 對齊版本號(參考官方相容性矩陣) |
| ConnectTimeout | 網路不通、防火牆 | 檢查連線、Proxy 設定 |
整合 SonarQube API 能將程式碼品質指標納入 CI/CD 管線、自動化報表、品質閘門決策,是 DevOps 落地的關鍵環節之一。