SonarQube 提供 REST API 讓外部系統整合程式碼品質指標。本文示範使用官方 sonar-ws-client Java 客戶端,透過 ResourceQuery 獲取專案的 violations(違規數)與 lines(程式碼行數)指標,並給出 Maven 依賴配置與完整程式碼範例。

<dependencies>
<!-- SonarQube Web Service Client -->
<dependency>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-ws-client</artifactId>
<version>4.3</version> <!-- 建議與 Server 版本一致 -->
</dependency>
<!-- HTTP Client (Client 4.x 相容) -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
import org.sonar.wsclient.Sonar;
import org.sonar.wsclient.connectors.HttpClient4Connector;
import org.sonar.wsclient.host.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 HOST = "https://your-sonarqube:9000";
private static final String USER = "admin";
private static final String PASS = "admin";
private static final String PROJECT_KEY = "com.example:my-project";
private static final String[] METRICS = {"violations", "lines", "ncloc", "functions", "classes", "files"};
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
// 1. 建立連接器
Sonar sonar = new Sonar(
new HttpClient4Connector(
new Host(HOST, USER, PASS)
)
);
// 2. 建立查詢:指定專案鍵與指標
ResourceQuery query = ResourceQuery.createForMetrics(PROJECT_KEY, METRICS);
query.setIncludeTrends(true); // 包含趨勢資料
// 3. 執行查詢
Resource resource = sonar.find(query);
if (resource == null) {
System.err.println("Project not found: " + PROJECT_KEY);
return;
}
// 4. 解析指標
List measures = resource.getMeasures();
for (Measure measure : measures) {
String key = measure.getMetricKey();
double val = measure.getValue();
System.out.printf("%s: %s%n", key, df.format(val));
}
// 5. 額外:取得特定指標的歷史趨勢
for (Measure measure : measures) {
if (measure.getTrend() != null) {
System.out.printf("%s trend: %s%n", measure.getMetricKey(), measure.getTrend());
}
}
}
}
| 指標鍵 | 中文名稱 | 含義 | 典型用途 |
|---|---|---|---|
violations | 違規總數 | 所有規則違反項目計數(含 Blocker/Critical/Major/Minor/Info) | 品質紅燈門檻 |
lines | 總行數 | 包含空白行、註解行的物理行數 | 專案規模估算 |
ncloc | 非註解程式碼行數 | 實際邏輯行數 (Non-Commenting Lines of Code) | 生產力/技術債密度分母 |
functions | 函數/方法數 | 複雜度參考 | |
classes | 類別數 | 架構規模參考 | |
files | 檔案數 | ||
duplicated_lines_density | 重複程式碼密度 | 重複行數 / ncloc | 重構優先級 |
coverage | 測試覆蓋率 | Line coverage % | 品質門檻核心指標 |
| 問題 | 原因 | 解決 |
|---|---|---|
| 401 Unauthorized | Token 過期/權限不足 | 使用 User Token (SonarQube 7.8+) 替代密碼 |
| 找不到專案 | Project Key 錯誤 | 確認專案設定頁面的 Project Key,區分大小寫 |
| 指標值為空 | 尚未掃描/掃描失敗 | 檢查 Scanner 執行日誌,確認分析成功 |
| 版本不相容 | Client 版本與 Server API 不符 | Client 版本鎖定為 Server 主版本號 (如 9.9.x → client 9.9) |
透過 SonarQube Web API 程式化獲取品質指標,能將程式碼品質納入自動化治理體系:阻擋不合格合併請求、觸發技術債務警示、生成管理儀表板,讓品質可視、可控、可改善。