kotlingradlebytecodeopenjpa

Calling PCEnhancerTask from Kotlin in Gradle


I need to call the OpenJPA PCEnhancerTask class from Kotlin instead of Groovy. The following code works just fine (based on a previous solution documented here):

def openJPAClosure = {
    def entityFiles = sourceSets.main.output.classesDirs.asFileTree.matching {
        include 'com/company/persist/*Entity.class'
    }
    println "Enhancing with OpenJPA:"
    entityFiles.getFiles().each {
        println it
    }
    ant.taskdef(
            name : 'openjpac',
            classpath : sourceSets.main.runtimeClasspath.asPath,
            classname : 'org.apache.openjpa.ant.PCEnhancerTask'
    )
    ant.openjpac(
            classpath: sourceSets.main.runtimeClasspath.asPath,
            addDefaultConstructor: false,
            enforcePropertyRestrictions: true) {
        entityFiles.addToAntBuilder(ant, 'fileset', FileCollection.AntType.FileSet)
    }
}

I was looking at the documentation on how to call Ant tasks from Gradle but I could not translate all the necessary steps using the GroovyBuilder. So instead I tough of calling the PCEnhancer directly:

fun openJPAEnrich() {
    val entityFiles = sourceSets.main.get().output.classesDirs.asFileTree.matching {
        include("com/company/persist/*Entity.class")
    }
    println("Enhancing with OpenJPA, the following files...")
    entityFiles.getFiles().forEach() {
        println(it)
    }
    org.apache.openjpa.ant.PCEnhancerTask.main(asList(entityFiles))
}

But it complains about not being able to find org.apache.openjpa in the classpath (but is it listed as a compilation dependency)

My questions are:


Solution

  • So I ended making it work with a custom JavaExec Gradle task:

    tasks.create<JavaExec>("openJPAEnrich") {
        val entityFiles = sourceSets.main.get().output.classesDirs.asFileTree.matching {
            include("com/company/persist/*Entity.class")
        }
        println("Enhancing with OpenJPA, the following files...")
        entityFiles.files.forEach() {
            println(it)
        }
        classpath = sourceSets.main.get().runtimeClasspath
        main = "org.apache.openjpa.enhance.PCEnhancer"
        args(listOf("-enforcePropertyRestrictions", "true", "-addDefaultConstructor", "false"))
        entityFiles.forEach { classFile -> args?.add(classFile.toString())}
    
    }
    
    I was tempted to build my own custom Gradle task but for this felt overkill.
    
    Thanks.
    
    --Jose