19

My build.gradle is currently:

project(':rss-middletier') {
    apply plugin: 'java'

    dependencies {
        compile project(':rss-core')
        compile 'asm:asm-all:3.2'
        compile 'com.sun.jersey:jersey-server:1.9.1'
        compile group: 'org.javalite', name: 'activejdbc', version: '1.4.9'
    }

    jar {
        from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
            exclude "META-INF/*.SF"
            exclude "META-INF/*.DSA"
            exclude "META-INF/*.RSA"
        }
        manifest { attributes 'Main-Class': 
'com.netflix.recipes.rss.server.MiddleTierServer' }
    }
}

But rather than packaging these compiled classes into a jar directly, I'd like to instrument them first by running the following task:

task instrument(dependsOn: 'build', type: JavaExec) {
    main = 'org.javalite.instrumentation.Main'
    classpath = buildscript.configurations.classpath
    classpath += project(':rss-middletier').sourceSets.main.runtimeClasspath
    jvmArgs '-DoutputDirectory=' + project(':rss-middletier').sourceSets
        .main.output.classesDir.getPath()
}

Only after I have instrumented these classes, I will then want to package them into a JAR file. Is there a way so that I can do this instrumentation before the packaging?

Thanks a lot!!!

Hongyi Li
  • 1,059
  • 2
  • 11
  • 19
  • here is an example Gradle project: https://github.com/javalite/activejdbc-gradle/. If you execute: `gradle clean build jar`, it will produce a jar file with instrumented classes – ipolevoy Jul 23 '14 at 16:26
  • use configurations { jar } then jar.doFirst { dependsOn instrument } – AKS Jul 23 '14 at 16:41

2 Answers2

27

Finally figured out the way to do it!

task instrument(type: JavaExec) {
    //your instrumentation task steps here
}
compileJava.doLast {
    tasks.instrument.execute()
}
jar {
    //whatever jar actions you need to do
}

Hope this can prevent others from being stuck on this problem for days :)

Hongyi Li
  • 1,059
  • 2
  • 11
  • 19
  • Not all tasks have a method called `execute`. You can use `finalizedBy` to specify any task to be run after compilation however it won't add the new task to the dependency tree for tasks that depend on `compileJava` so you might get errors. I've raised the latter https://github.com/gradle/gradle/issues/23814 – mjaggard Feb 07 '23 at 17:46
-1

This is a bit irrelevant to what is asked in the question. But thought to mention by thinking it may help to someone.

I was trying to execute a task with the type Copy before the Jar task.

task copyFilesTask(type: Copy) {

   //do whatever you want in here
}

compileJava.dependsOn(copyFilesTask)

jar {
    // jar actions. example below
    //manifest {
    //    attributes 'Main-Class': '<target-class-name-here>'
    //}
}

I have done this before the compileJava task because I need the relevant files to be available at the time of creating jar archive.

ThilankaD
  • 1,021
  • 1
  • 13
  • 24