Skip to content
Advertisement

Gradle: Exclude file from resourses and add it from different folder

I am trying to build a jar file with Gradle. I have some resource files (like log4j2 and persistent.xml) into the src/main/resources that I want to exclude when I was built the jar, on contrary I have the same files (with different content in a project directory) and I want to copy these files rather than the src/main/resource files.

Into my gradle.build

from jar {
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    // The parent folder is: src/main/resources for the (1) and (2)
    exclude('META-INF/persistence.xml') // (1)
    exclude('log4j2.xml') // (2)
  
    from('distributions/persistence.xml'){ // (3)
        into 'META-INF'
        filter(ReplaceTokens, tokens: [TEST_PARAM: 'tmp_value1'])
    }
    
    from('distributions/log4j2.xml') { // (4)
        filter(ReplaceTokens, tokens: [TEST_PARAM: 'tmp_value1'])
    }
}

So I exclude the two files manually (1), (2), and then I added (3), (4). When I extract the jar, I can find the persistence.xml but not the log4j2.xml.

And my question is, why does this happen?

(PS)

If i replace the (1), (2) with

processResources.exclude('*')

Into jar are placed both the persistence.xml but not the log4j2.xml.

Thank’s in advance.

Advertisement

Answer

Accordingly to this documentation: Any exclusion pattern overrides any inclusions, so if a file or directory matches at least one exclusion pattern, it won’t be included, regardless of the inclusion patterns.

It seems like the behavior you observe is caused by how file exclusion is handled by gradle. The way you did it works for the files copied to a subfolder in jar file. For some reason it does not work for files copied to the root folder of jar file.

You can achieve what you want with this configuration:

jar {
  from('distributions') {
    include("**/*.xml")
  }

  eachFile {
    if (it.file.path =~ "build/resources/main/") {
      // exclude resources copied from build/resources/main/
      it.exclude()
    }
  }
}

Here’s the project tree I used since mine can be different from the project you are working on:

├── build.gradle
├── distributions
│   ├── META-INF
│   │   └── persistence.xml
│   └── log4j2.xml
└── src
    └── main
        ├── java
        │   └── Main.java
        └── resources
            ├── META-INF
            │   └── persistence.xml
            └── log4j2.xml

This solution is based on these discussions:

  1. https://discuss.gradle.org/t/how-to-override-where-some-files-are-written-to-in-the-jar-file/5282
  2. How do you force Gradle to overwrite a resource file in a custom WAR task?
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement