簡體   English   中英

SonarQube。 自定義規則需要訪問文件

[英]SonarQube. Custom rule needs to access to file

我在需要從外部文件提取數據的地方實施了規則。 我將此文件放在資源文件夾中,並按以下結構進行提取:

CustomRuleCheck.class.getResource(/com/packagename/file.json)

在進行JUnit測試期間,一切正常,但是當我運行集成測試時,無法獲得此文件。

ava.io.FileNotFoundException: file:/home/username/.sonar/cache/587ed81cbc083da501c4bfdcefd65f35/sonar-plugin-0.0.10-SNAPSHOT.jar_unzip/META-INF/lib/custom-checks-0.0.10-SNAPSHOT.jar!/com/packagename/file.json (No such file or directory)

我跟隨着指向的URL,結果發現文件夾/home/username/.sonar/cache/587ed81cbc083da501c4bfdcefd65f35/sonar-plugin-0.0.10-SNAPSHOT.jar_unzip/META-INF/lib/包含custom-checks-0.0.10-SNAPSHOT.jar ,此jar內有必要的文件。 而且我不知道如何提取它。 請問你能幫幫我嗎?

據我了解,(感謝@JosefProcházka), sonar-plugin會在運行時加載CustomRules,並從custom-checks.jar上傳特定規則。 我找到了一個決定如何從custom-checks.jar中的custom-checks.jar中提取資源文件(自定義規則放置在checks.jar )。 我寫下了以下util方法:

public class JarResourcesUtils {

    public static File extractFileFromJar(String path) throws IOException {
        String resourcePath = JarResourcesUtils.class.getResource(path).getPath();
        String jarPath = resourcePath.replace("!" + path, "").replace("file:", "");

        try (JarFile jarFile  = new JarFile(jarPath)){
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
              JarEntry entry = entries.nextElement();
              String entryName = "/" + entry.getName();
              if (entryName.equals(path)) {
                  InputStream inputStream = jarFile.getInputStream(entry);
                  File file = File.createTempFile(entryName.replaceAll("//", "_"), ".tmp");
                  FileUtils.copyToFile(inputStream, file);
                  return file;
              }
           }
           return null;
         }
     }
}

然后在CustomRules中,我們可以獲取以下文件:

File resourceFile = JarResourcesUtils.extractFileFromJar("/com/packagename/file.json");

當然,必須根據Maven約定將文件放置在資源目錄中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM