Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle - extract file from depended jar

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!

like image 509
qwazer Avatar asked Nov 12 '12 06:11

qwazer


2 Answers

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'
    }
}
like image 121
Peter Niederwieser Avatar answered Oct 04 '22 15:10

Peter Niederwieser


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
    }
}
like image 21
gavenkoa Avatar answered Oct 04 '22 17:10

gavenkoa