SonarQube. Custom rule needs to access to file

I implemented rule where I needed to extract data from external file. I put this file in resources folder and extract it with the following construction:


During JUnit testing is everething ok, but when I run an integration testing I cannot get this file. 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)

I followed to pointed url and it turned out that folder /home/username/.sonar/cache/587ed81cbc083da501c4bfdcefd65f35/sonar-plugin-0.0.10-SNAPSHOT.jar_unzip/META-INF/lib/ contains custom-checks-0.0.10-SNAPSHOT.jar and this jar has necessary file inside. And I don’t have any idea how to extract this. Could you help me please?


As I understood,(thanks to @JosefProcházka) sonar-plugin loads CustomRules in runtime uploading the particular rules from custom-checks.jar. I find a decision how extract resource files from custom-checks.jar in CustomRules (Custom rules is placed in checks.jar). I’ve written down the following util method:

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;

Then inside a CustomRules we can get this file:

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

Of cource, file must be placed in resources directory according to maven conventions

Leave a Reply

Your email address will not be published. Required fields are marked *