Custom task invoking parent class method instead of user of custom task

I’d like to simplify the usage of my custom task, that extends Exec task.

My implementation (simplified for this example, but still works without problems) is following:

`class ImportCert extends Exec {
    String pathToKeyStore = "${System.env.JAVA_HOME}/jre/lib/security/cacerts"
    String storepass = "changeit"
    String pathToCert
    String certAlias

    def importCert() {
        println 'Importing ' + pathToCert + " (with alias " + certAlias + ") to keystore " + pathToKeyStore
        //commandLine(getCommandLine()) // I'd like to call this method from this class, not from the task

    public List getCommandLine() {
        return ['keytool', '-import', '-noprompt', '-keystore', pathToKeyStore, '-storepass', storepass, '-alias', certAlias, '-file', pathToCert]

task importDemoCert(type:ImportCert) {
    pathToCert = "$rootProject.projectDir/etc/"
    certAlias = ""
    commandLine(getCommandLine()) // XXX: i'd like to get rid of this line

While current implementation calls commandLine(getCommandLine()) from the task, that uses ImportCert task, I’d like to be able to avoid having this line everywhere where i use ImportCert task.

So I’m wondering, if it is possible to have parent class invoke that method instead of every task that uses it.

I tried moving commandLine(getCommandLine()) from the task to ImportCert.importCert task, but that ends up with failure:

Execution failed for task ':importDemoCert'.
> execCommand == null!

Is there some other method that i should use instead?

Best Regards,

A few options…

You could override exec() (instead of using importCert()) and call super.exec() at the end of your method. Since you’re extending Exec, you have two methods with @TaskAction and the order isn’t guaranteed.

You could add a doFirst action that sets the command line. This is sort of like you’re trying now, but doFirst guarantees that your action happens before Exec’s.

If it doesn’t make sense for a user to ever configure anything else related to the Exec task, I wouldn’t extend Exec. Extend DefaultTask and just make your @TaskAction method use project.exec {}. This is basically the classic composition-over-inheritance lesson.

1 Like