Gradle: Executing task in subproject programmatically
<p>My WAR file should contain Java source files from components.
In my root project build.gradle I am executing tasks in subprojects programmatically:</p>

<pre><code>apply plugin: 'war'

jar.enabled = false
war {
    // - Copy Java source files to the folder corresponding to the component;
    into("/") { from { collectFilesFromCopyTask('copySourceFiles') } }
}

// Collects files from destinationDirs of copy tasks with matching taskName
def collectFilesFromCopyTask(taskName) {
    FileCollection collectedFiles = files{}

    // for each task in subprojects
    subprojects.each {project -&gt;
        project.tasks.withType(Copy).matching { task -&gt; task.name.equals( taskName ) }.each { copyFilesTask -&gt;
            println 'copyFilesTask.destinationDir=' + copyFilesTask.destinationDir

            // execute task
            copyFilesTask.execute()

            // add destinationDir of the task to the collected files
            collectedFiles += files(copyFilesTask.destinationDir)
        }
    }

    return collectedFiles
}
</code></pre>

<p>In subproject I have task:</p>

<pre><code>task copySourceFiles(type: Copy) {
    destinationDir = file(project.buildDir.name + '/sourceFiles')

    into('componentName') {
        from(project.projectDir)
        exclude('build')
        exclude('bin')
        exclude('src/main/webapp')
        exclude('.gradle')
    }
}
</code></pre>

<p>Console output:</p>

<pre><code>[sts] -----------------------------------------------------
[sts] Starting Gradle build for the following tasks: 
[sts]      clean
[sts]      build
[sts] -----------------------------------------------------
copyFilesTask.destinationDir=&lt;...&gt;application1\build\sourceFiles
:clean
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:war
copyFilesTask.destinationDir=&lt;...&gt;application1\build\sourceFiles
copyFilesTask.destinationDir=&lt;...&gt;application1\build\sourceFiles
copyFilesTask.destinationDir=&lt;...&gt;application1\build\sourceFiles
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build
</code></pre>

<p>, which means that collectFilesFromCopyTask() is executed 4 times.
It should be executed only once, from WAR task.</p>