2

I am trying to run a Java class as a gradle task.

I have added this to my build.gradle:

task(downloadKeystore, dependsOn: 'classes', type: JavaExec) {
    main = 'com.orbitbenefits.keystore.KeystoreDownloader'
}

However, when I run on the command line gradle downloadKeystore, it fails with the following error:

:Noa:downloadKeystoreError: Could not find or load main class com.orbitbenefits.keystore.KeystoreDownloader

So I have added a classpath to my task as specified in this question:

task(downloadKeystore, dependsOn: 'classes', type: JavaExec) {
    main = 'com.orbitbenefits.keystore.KeystoreDownloader'
    classpath = sourceSets.main.runtimeClasspath
}

However, this is large legacy project with extremely long classpath, so when I run gradle downloadKeystore I get another error:

Caused by: java.io.IOException: Cannot run program "C:\Program Files\Java\jdk1.8.0_77\bin\java.exe" (in directory "C:\Users\pawlakj\IdeaProjects\noa\Noa"): CreateProcess error=206, The filename or extension is too long

So I have modified my sourceSets in build.gradle so it now looks like this:

sourceSets {
    main {
        java {
            srcDirs(...)
        }
        resources {
            srcDirs(...)
        }
    }

    keystore {
        java {
            srcDirs = ['src/test/java/com/orbitbenefits/keystore']
        }
    }

    test {
        java {
            srcDirs(...)
        }
        resources {
            srcDirs(...)
        }
    }
}

...

task(downloadKeystore, dependsOn: 'classes', type: JavaExec) {
    main = 'com.orbitbenefits.keystore.KeystoreDownloader'
    classpath = sourceSets.keystore.runtimeClasspath
}

This works on the command line, however when I run gradle refresh in IntelliJ, it generally breaks the project. It looks like this:

Broken IntelliJ

But it should look like this:

Not-broken IntelliJ

I have tried manually setting test/src root directories but it doesn't really work and also I don't want other developers to have to do this.

I have also tried setting classpath manually using something like:

classpath = classpath('src/test/java/com/orbitbenefits/keystore')

But I couldn't make it work (gradle doesn't like it).

Question

I need to solve only one of these two problems:

How can I define classpath manually?

OR

How can I make IntelliJ to not mess up project structure when using its gradle refresh button?

Community
  • 1
  • 1
Jaroslaw Pawlak
  • 5,538
  • 7
  • 30
  • 57

1 Answers1

1

Your IntelliJ is having a problem with srcDirs = ['src/test/java/com/orbitbenefits/keystore'] because src/test/java is already a folder containing some source.

One solution could be to define a new folder sibling to src where you have your KeystoreDownloader class and then import the keystore as follows:

keystore {
    java {
        srcDirs = ['keystore']
    }
}
daemon_nio
  • 1,446
  • 1
  • 16
  • 19