Gradle - extract file from depended jar

2019-04-06 15:22发布

问题:

I want to extract file "default.jasperreports.properties" from depended jasperreports.jar and put it in zip distribution with new name "jasperreports.properties"

Sample gradle build:

apply plugin: 'java'

task zip(type: Zip) {
    from 'src/dist'
  //  from configurations.runtime
    from extractFileFromJar("default.jasperreports.properties");
    rename 'default.jasperreports.properties', 'jasperreports.properties'

}

def extractFileFromJar(String fileName) {
    //    configurations.runtime.files.each { file -> println file} //it's not work 
    // not finished part of build file
    FileTree tree = zipTree('someFile.zip')
    FileTree filtered = tree.matching {
        include fileName
    }

}

repositories {
    mavenCentral()
}

dependencies {
    runtime 'jasperreports:jasperreports:2.0.5'
}

How to get FileTree in extractFileFromJar() from dependency jasperreports-2.0.5.jar?

In script above I use

FileTree tree = zipTree('someFile.zip')

but want to use somethink like (wrong, but human readable)

FileTree tree = configurations.runtime.filter("jasperreports").singleFile.zipTree

PS: Try to call

def extractFileFromJar(String fileName) {
    configurations.runtime.files.each { file -> println file} //it's not work 
...

but it doesn't work with exception

You can't change a configuration which is not in unresolved state!

回答1:

Here is a possible solution (sometimes code says more than a thousand words):

apply plugin: "java"

repositories {
    mavenCentral()
}

configurations {
    jasper
}

dependencies {
    jasper('jasperreports:jasperreports:2.0.5') { 
        transitive = false
    }
}

task zip(type: Zip) {
    from 'src/dist'
    // note that zipTree call is wrapped in closure so that configuration
    // is only resolved at execution time
    from({ zipTree(configurations.jasper.singleFile) }) {
        include 'default.jasperreports.properties'
        rename 'default.jasperreports.properties', 'jasperreports.properties'
    }
}


回答2:

Alternative solution:

configurations {
    batch
}

dependencies {
    batch 'org.springframework.batch:spring-batch-core:3.0.8.RELEASE' { 
        transitive = false
    }
}

def extractBatchSql(path) {
    def zipFile = configurations.batch.find { it =~ /spring-batch-core/ }
    def zip = new java.util.zip.ZipFile(zipFile)
    def entry = zip.getEntry(path)
    return zip.getInputStream(entry).text
}

task tmp() {
    dependsOn configurations.batch

    doLast {
        def delSql = extractBatchSql("org/springframework/batch/core/schema-drop-oracle10g.sql")
        println delSql
    }
}