繁体   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