confusion on what tasks --all prints out - gradle

I have this when I execute "gradle tasks --all"
assemble - Assembles the outputs of this project. [jar]
toneserver:assemble - Assembles the outputs of this project. [toneserver:jar, webserver:jar]
toneserver:copyJars
toneserver:zip
webserver:assemble - Assembles the outputs of this project. [webserver:jar]
webserver:versionFile
webserver:zip
What I really really don't get is I have toneserver:zip depending on toneserver:jar and I have webserver:zip depending on webserver:jar but this tasks --all is not showing those dependencies. Why is this? and how to get it to truly show the dependencies?
My full gradle file is below(and yes I need to move the apply plugin stuff still out of all projects into subprojects section and other
allprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
//override gradle's default output directory(build) on every project as it conflicts with
//our build script called build causing failures.
buildDir = 'output'
repositories {
mavenCentral()
}
if (project.hasProperty('myVersion')) {
project.ext.realVersion = project.myVersion
project.version = project.myVersion
} else {
project.ext.realVersion = 'Developer-Build'
project.version = 'Developer-Build'
}
test {
beforeTest { desc ->
println "Executing test ${desc.name} [${desc.className}]"
}
}
task hello << { task -> println "I'm $task.project.name" }
build << { task -> println "MASTER: I'm building now" } //"building with classpath=$sourceSets.main.compileClasspath.files"
}
project(':webserver') {
//play does not follow maven/gradle standard of src/main/java and src/test/java :( :(
//so we override the directories here...(we should put test in the sourceSets.test.java.srcDirs instead)
sourceSets.main{
java.srcDirs = ['app', 'test']
resources.srcDirs = ['app']
}
dependencies {
compile fileTree(dir: 'lib', include: '*.jar')
compile fileTree(dir: 'play-1.2.4/framework/lib', include: '*.jar')
compile fileTree(dir: 'play-1.2.4/framework', include: 'play-*.jar')
}
//MOVE this into allprojects to be run by both toneserver and webserver to put a file there...
task versionFile() << {
File f = new File('webserver/output/version');
f.mkdirs()
File v = new File(f, 'version'+project.ext.realVersion)
println('output version file='+v.getAbsolutePath())
v.createNewFile()
}
task zip(type: Zip) {
archiveName 'dashboard-'+project.version+'.zip'
from('output/version') {
into('webserver')
}
from('..') {
exclude '**/*.pyc'
exclude '**/*.class'
exclude '**/samples-and-tests/**'
exclude '**/play-1.2.4/documentation/**'
exclude 'webserver/conf/logback.xml'
include 'webserver/run*.sh'
include 'webserver/lib/**'
include 'webserver/app/**'
include 'webserver/conf/**'
include 'webserver/play-1.2.4/**'
include 'webserver/public/**'
}
rename 'prod.(.*)', '$1'
}
zip.dependsOn('versionFile')
zip.dependsOn('jar')
assemble.dependsOn('zip')
//playframework has it's own generation of .classpath and .project fils so do not
//overwrite their versions. NEED to call "play.bat eclipsify" here...
task eclipse(overwrite: true) << {
if (System.properties['os.name'].toLowerCase().contains('windows')) {
println "*** WINDOWS "
def result = exec {
commandLine 'cmd', '/c', 'play-1.2.4\\play.bat eclipsify'
}
} else {
println "*** NOT WINDOWS "
def result = exec {
commandLine './play-1.2.4/play eclipsify'
}
}
}
}
project(':toneserver') {
project.ext.genLibDir = file('output/thirdpartylibs')
configurations {
all*.exclude module: 'log4j'
}
dependencies {
compile 'com.google.inject:guice:3.0'
compile 'com.google.protobuf:protobuf-java:2.4.1'
//weird, why is their maven not working(we drop it in the directory instead)...
//compile 'org.asteriskjava:asterisk-java:1.0.0.M3'
//to be erased as soon as we get the chance...(we should try this NOW and see if it is needed anymore)
compile 'commons-configuration:commons-configuration:1.8'
compile 'org.bouncycastle:bcpg-jdk16:1.46'
compile project(':webserver')
//gradle is not sucking in transitive dependencies when they exist in another project so we suck them
//in ourselves here...
compile fileTree(dir: '../webserver/play-1.2.4/framework/lib', include: '*.jar')
compile fileTree(dir: '../webserver/lib', include: '*.jar')
compile fileTree(dir: '../webserver/play-1.2.4/framework', include: 'play-*.jar')
compile 'org.bouncycastle:bcpg-jdk16:1.46'
testCompile 'junit:junit:4.11'
}
task generateSources {
project.ext.outputDir = file("$buildDir/generated-src")
outputDir.exists() || outputDir.mkdirs()
if (System.properties['os.name'].toLowerCase().contains('windows')) {
println "*** WINDOWS "
def result = exec {
commandLine 'cmd', '/c', '..\\tools\\protoc\\protoc.exe', '--java_out=output\\generated-src', 'src\\schemas\\agentbridge.proto'
}
} else {
throw new RuntimeException("DARN, protoc only works on windows :( :( right now")
}
}
compileJava.dependsOn("generateSources")
sourceSets {
main {
java {
srcDir 'output/generated-src'
}
}
}
tasks.eclipse.dependsOn("generateSources")
task copyJars(type: Copy) {
from(configurations.compile) {}
into genLibDir
}
task initconfig(type:Copy) {
from('src/staging/toneserver') {
include '**/*'
}
into 'output/staging'
}
task zip(type: Zip) {
archiveName 'toneserver-'+project.version+'.zip'
from('src/staging') {
include 'toneserver/**'
}
from('output/thirdpartylibs') {
into('toneserver/lib')
}
from('output/version') {
into('webserver')
}
}
zip.dependsOn('copyJars')
zip.dependsOn('jar')
assemble.dependsOn('zip')
}
//overwrite the eclipse target so that no .classpath ends up in stserver directory
task eclipse(overwrite: true) {
}

gradle tasks --all shows all tasks, but only first-level task dependencies. I agree that it would be useful to have a way to visualize the whole task graph, but it's not something that Gradle currently offers out-of-the-box.

Related

Jacoco | Gradle | Exclude from aggregated modules

I have a Java-Gradle project that has multiple modules, meaning multiple build.gradle files and multiple test folders.
I have a main build.gralde and I succeeded to aggregate all the multi jacoco reports to one main report using the configuration below at my main build.gradle.
but now I want to exclude some of packages / classes from the aggregated modules.
How do I do that?
you can see also my tries below
apply plugin: 'jacoco'
apply plugin: 'java'
def otherProjects = [':module1', ':module2']
otherProjects.each {
// ensure other projects evaluated first so sourceSets are configured
evaluationDependsOn it
}
jacoco {
toolVersion = "0.8.4"
reportsDir = file("$buildDir/jacoco")
}
jacocoTestReport {
FileTree sourceTree = files().asFileTree
FileTree classTree = files().asFileTree
otherProjects.each {
sourceTree += project(it).sourceSets.main.allJava
classTree += project(it).sourceSets.main.output.asFileTree
}
additionalSourceDirs = sourceTree
additionalClassDirs = classTree
reports {
html.enabled true
html.destination file("${buildDir}/jacocoHtml")
}
// try 1
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it, exclude: '/com/packege_from_module1/**')
})
}
// try 2
afterEvaluate {
additionalSourceDirs = files(additionalSourceDirs.files.collect {
sourceTree(dir: it, exclude: 'com/packege_from__module1/**')
})
}
// try 3
afterEvaluate {
additionalSourceDirs = files(additionalSourceDirs.files.collect {
classTree(dir: it, exclude: 'com/packege_from__module1/**')
})
}
}
Given
a/src/main/java/A.java
class A {
}
a/src/test/java/ATest.java
import org.junit.Test;
public class ATest {
#Test
public void a() {
}
}
b/src/main/java/B.java
class B {
}
b/src/test/java/BTest.java
import org.junit.Test;
public class BTest {
#Test
public void b() {
}
}
settings.gradle
rootProject.name = 'example'
include 'a'
include 'b'
and build.gradle
allprojects {
apply plugin: 'java'
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.3"
}
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.12'
}
}
task jacocoAggregateReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) {
dependsOn = subprojects.test
sourceDirectories = files(subprojects.sourceSets.main.allSource.srcDirs)
classDirectories = files(subprojects.sourceSets.main.output)
executionData = files(subprojects.jacocoTestReport.executionData)
}
using Gradle 4.10.3 or 5.4.1 execution of gradle jacocoAggregateReport will produce following report in directory build/reports/jacoco/jacocoAggregateReport/html/index.html
Now let's exclude class file A.class from report by changing
classDirectories = files(subprojects.sourceSets.main.output)
in build.gradle on
classDirectories = files(subprojects.sourceSets.main.output).asFileTree.matching {
exclude 'A.class'
}
and execution of gradle jacocoAggregateReport will produce
Your attempts did not worked, because report is constructed for all class files from both classDirectories and additionalClassDirs - no exclusion from classDirectories and additionalClassDirs in attempts 2 and 3, no exclusion from additionalClassDirs in attempt 1.

Execute a task only if a particular task is run

I want the task setupDB to execute if and only if the task fatJar or slimJar is run.
But after adding gradle.taskGraph.whenReady, commandLine './scripts/configureSQLiteDB.sh' is never running for any task.
Here is my code for the setupDB task:
//download bigg.sqlite if not present
task setupDB {
gradle.taskGraph.whenReady { graph ->
if (!project.file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists()
&& (graph.hasTask(slimJar)|| graph.hasTask(fatJar))) {
doFirst {
exec {
println "Setup DB"
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
}
}
You can also view the build.gradle file:
apply plugin: "java"
defaultTasks "clean", "fatJar"
// Java versions for compilation and output
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
archivesBaseName = "ModelPolisher"
version = "1.7"
sourceSets {
main.java.srcDirs = ["src"]
main.resources.srcDirs = ["resources"]
main.resources.excludes = ["**/bigg.zip"]
test.java.srcDirs = ["test"]
}
repositories {
mavenCentral()
maven { url "http://www.ebi.ac.uk/~maven/m2repo" }
maven { url "http://jsbml.sourceforge.net/m2repo/" }
// local dependencies
flatDir {
dirs "lib/de/zbit/SysBio/1390"
}
}
dependencies {
compile "org.sbml.jsbml:jsbml:1.4"
compile "de.zbit:SysBio:1390"
compile "org.xerial:sqlite-jdbc:3.21.0"
compile "org.postgresql:postgresql:42.2.2"
compile "org.biojava:biojava-ontology:5.0.0"
compile "com.diffplug.matsim:matfilerw:3.0.1"
compile "com.fasterxml.jackson.core:jackson-core:2.9.9"
compile "com.fasterxml.jackson.core:jackson-databind:2.9.9"
testCompile "org.junit.jupiter:junit-jupiter-engine:5.1.0"
}
// config for all jar tasks
tasks.withType(Jar) {
dependsOn test
destinationDir = file("$rootDir/target")
manifest {
attributes(
"Version": version,
"Implementation-Title": "ModelPolisher",
"Implementation-Version": version,
"Specification-Vendor": "University of California, San Diego",
"Specification-Title": "ModelPolisher",
"Implementation-Vendor-Id": "edu.ucsd.sbrg",
"Implementation-Vendor": "University of California, San Diego",
"Main-Class": "edu.ucsd.sbrg.bigg.ModelPolisher"
)
}
}
// with dependencies
task fatJar(type: Jar) {
baseName = project.name + "-fat"
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
//with dependencies, without bigg.sqlite
task lightJar(type: Jar) {
exclude("**/bigg.sqlite")
baseName = project.name + "-noDB"
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
// without dependencies and bigg.sqlite
task bareJar(type: Jar) {
exclude("**/bigg.sqlite")
baseName = project.name + "-slim-noDB"
with jar
}
// without dependencies, bigg.sqlite included
// not included in release
task slimJar(type: Jar) {
baseName = project.name + "-slim"
with jar
}
// zip lib folder for release
task zipLibs(type: Zip) {
from "lib"
into "lib"
include "**/**"
archiveName = "lib.zip"
destinationDir = file("target/")
}
// zip script files for release
task zipScripts(type: Zip) {
from "scripts"
into "scripts"
include "**/**"
archiveName = "scripts.zip"
destinationDir = file("target/")
}
// create all three jars for release
task release() {
dependsOn fatJar
dependsOn bareJar
dependsOn lightJar
dependsOn tasks["zipLibs"]
dependsOn tasks["zipScripts"]
// necessary, as order is not defined by dependsOn
bareJar.mustRunAfter classes
// slimJar.mustRunAfter bareJar
lightJar.mustRunAfter slimJar
fatJar.mustRunAfter lightJar
}
// clean up target directory
clean.doFirst {
file(".gradle").deleteDir()
file("target").deleteDir()
}
//download bigg.sqlite if not present
task setupDB {
gradle.taskGraph.whenReady { graph ->
if (!project.file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists()
&& (graph.hasTask(slimJar)|| graph.hasTask(fatJar))) {
doFirst {
exec {
println "Setup DB"
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
}
}
// bump jar version in travis.yml
if (project.file(".travis.yml").exists()) {
task bumpVersionTravis() {
replaceVersion(".travis.yml")
}
processResources.dependsOn bumpVersionTravis
}
// bump jar version in ModelPolisher.sh
if (project.file("./scripts/ModelPolisher.sh").exists()) {
task bumpVersionMP() {
replaceVersion("./scripts/ModelPolisher.sh")
}
processResources.dependsOn bumpVersionMP
}
def replaceVersion(path) {
ArrayList<String> content = new ArrayList<>()
File travisFile = new File(path)
String MPVersion = /ModelPolisher.*\d{1,2}(.\d{1,2}){1,2}.jar/
travisFile.eachLine {
line ->
content.add(line.replaceAll(MPVersion, "ModelPolisher-fat-" +
"${version}.jar"))
}
BufferedWriter writer = new BufferedWriter(new FileWriter(travisFile))
content.each {
line -> writer.writeLine(line)
}
writer.close()
}
You seem to have the wrong idea about gradle configuration. You shouldn't be changing task behavior based on inputs. You should be configuring dependencies between tasks and also configuring task inputs/outputs to control the "up-to-date" behaviour.
Eg:
task slimJar(type:Jar) {
dependsOn 'setupDB'
...
}
task fatJar(type:Jar) {
dependsOn 'setupDB'
...
}
task setupDB {
outputs.upToDateWhen { file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists() }
doFirst {
println "Setup DB"
exec {
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
The following is also bad practice
if (project.file(".travis.yml").exists()) {
task bumpVersionTravis() {
replaceVersion(".travis.yml")
}
processResources.dependsOn bumpVersionTravis
}
The available tasks should NOT change based on files in your file system. They should always be there, regardless of your file system. You should instead set the "enabled" flag (or use task outputs) to control if the task executes or is skipped
Eg:
task bumpVersionTravis {
enabled = project.file(".travis.yml").exists()
doLast {
replaceVersion(".travis.yml")
}
}
processResources.dependsOn bumpVersionTravis

gradle tasks.withType does not find tasks defined in other file

I have two gradle files, setup.gradle and tests.gradle; each having two gradle tasks of custom type 'EMTest';
test.gradle applies the 'setup.gradle' as apply from: 'setup.gradle'
I want to configure all tasks of type EMTest; For that I added below code at end of tests.gradle
tasks.withType(EMTest) {
println it.name
}
But this only prints the name of tasks in the tests.gradle;
When I run
tasks.all {
println it.name + " " + it.class
}
It however lists the tasks name defined in setup.gradle and the type as EMTest_Decorated (for all 4 types)
NOTE: I use gradle 1.11 (no control over upgrade); What is the issue here ?
UPDATE On 09/Jun
Here is the main file :
apply plugin: 'java';
apply plugin: 'maven'
apply from: 'emcpsrvs_3n_setup.gradle'
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo" }
}
dependencies {
classpath group:"com.mycompany.myprod.mymodule", name: "TestInfraPlugin", version: "${testinfraVersion}", transitive: true
classpath group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version:'1.9.13'
classpath group: 'com.mycompany.myprod', name: 'common',version:'0.1'
classpath group: 'org.codehaus.jackson', name: 'jackson-core-asl', version:'1.9.13'
classpath group: 'com.oracle.weblogic',name: 'jettison-1.1', version: '12.1.2-0-0'
}
}
repositories {
/* To check if the jar is available in local maven repository */
mavenLocal()
maven {
url = "${artifactory_contextUrl}/repo"
}
}
apply plugin: 'TestInfraPlugin'
import com.mycompany.myprod.gradle.testinfra.tasks.EMTest;
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
testConfig group:'com.mycompany.myprod',name:'ui-integ-tests', version: '1.+'
testConfig group: 'com.mycompany.myprod', name: 'emaas-platform-tenant-sdk', version: '0.1+'
}
task unitTests(type: EMTest){
}
// Three tests are disabled due to JIRA-900
task tenantMgmtUITests(type: EMTest,dependsOn: [cleanSmall_deploy_3n_block,small_deploy_3n_block]) {
useWebdriver = true
small_deploy_3n_block.mustRunAfter ([cleanSmall_deploy_3n_block])
options.suiteXmlBuilder().suite('parallel': 'none','name': 'TenantManagementUI') {
test('name': 'TenantManagementUI') {
classes([:]) {
'class'('name': 'com.mycompany.package.MyTest')
}
}
}
}
small_deploy_3n_cleanup.mustRunAfter ([tenantMgmtUITests])
task emcpsrvs_tenant_mgmt_ui_3n(dependsOn: [tenantMgmtUITests,small_deploy_3n_cleanup])
Here is the 'emcpsrvs_3n_setup.gradle' which is being applied above
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
classpath group: 'com.mycompany.myprod.emdi', name: 'TestInfraPlugin', version: "${testinfraVersion}", transitive: true
}
}
apply plugin: 'TestInfraPlugin'
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
import com.mycompany.myprod.gradle.testinfra.tasks.EMTest;
ext.integDeployVersion='1.1+'
dependencies {
testConfig group: 'com.mycompany.myprod.test', name: 'smalldeployment', version: "${integDeployVersion}"
}
/* Setup EMaaS Small Deployment */
task small_deploy_3n_block(type: EMTest) {
outputs.upToDateWhen { false }
onlyIf {!System.env.SMALLDEPLOY_IGNORESETUP}
options.suiteXmlBuilder().suite('name': 'setup_3n_env') {
test('name': 'emaas_setup_small_deploy') {
classes([:]) {
'class'('name': 'mycompany.sysman.test.emaas.integ.EmaasSmallDeploy3n') {
methods([:]) {
'include' ('name': 'setupEmaasSmallDeploy')
}
}
}
}
}
useWebdriver = true
useRestAssured = true
}
/* Cleanup EMaaS Small Deployment */
task small_deploy_3n_cleanup(type: EMTest) {
onlyIf {!System.env.SMALLDEPLOY_IGNORESETUP}
options.suiteXmlBuilder().suite('name': 'setup_3n_env') {
test('name': 'emaas_setup_small_deploy') {
classes([:]) {
'class'('name': 'mycompany.sysman.test.emaas.integ.EmaasSmallDeploy3n') {
methods([:]) {
'include' ('name': 'logCollectionAndPostCleanup')
}
}
}
}
}
mustRunAfter ([small_deploy_3n_block])
}
And finally here is the snippet from TestInfraPlugin.groovy (The gradle plugin):
logger.debug "Configuring the EMTest task with default values."
project.afterEvaluate {
project.ext.testClassesDir = new File(project.properties['emdi.T_WORK'] + '/testClasses')
def testTasks = project.tasks.withType(EMTest)
if (testTasks != null && testTasks.size() == 0) {
logger.info "There are no tasks of type EMTest."
return
}
def extractTask = project.tasks.findByPath('extractTestClasses') ?:
project.task('extractTestClasses', type: ExtractConfiguration) {
configuration = project.configurations.testConfig
to = project.testClassesDir
}
/*
* 1. Adding the 'extractTask' to all EMTest, to ensure that 'extractTask' is run before any 'EMTest'.
* 2. For lazy evaluation of lrgConfig, we are NOT running the task here, but just adding as dependent task.
*/
testTasks.each { task ->
logger.debug "Adding dependsOn extractTask for task: ${task.name}"
task.dependsOn extractTask
}
} // end afterEvaluate
}
What is afterEvaluate{} block doing:
It checks if there are any tasks of type EMTest and if there are creates a task to extract a configuration (named testConfig). This extract task is added as dependency on all the tasks of type EMTest such that the extract task run as first task before running any other task.
What is happening
The extractTestClasses task is added as dependency to ONLY the two tasks unitTests and tenantMgmtUITests and thus the small_deploy_3n_block is getting executed before extractTestClasses resulting setup to fail, which in turn results test to fail.
When you reference tasks with no object it is implicitly using project.tasks.
tasks.withType(EMTest) {
println it.name
}
That is why you'll only get tasks from your current project.
To include all projects you can use:
allprojects {
tasks.withType(EMTest) { println it.name }
}
In this closure you are referencing it.tasks, where it loops over every individual project.
This will not work as expected since Gradle will probably not have loaded all of your sub-projects at this point, and not have reached every task define found during the full configuration phase. Therefore you must define the closure to run after all the projects are fully evaluated:
allprojects {
afterEvaluate {
tasks.withType(EMTest) { println it.name }
}
}

Defining custom ‘build’ task is deprecated when using standard lifecycle plugin has been deprecated and is scheduled to be removed in Gradle 3.0

I am facing an issue in my build.gradle script My script is bascially generatiing the POM file and then copy the artifact to other location as well under build/lib with different name.The issue which I am facing How to call the below build task beacuse it is generating the error.I am using gradle 2.3
Error:"Defining custom ‘build’ task is deprecated when using standard lifecycle plugin has been deprecated and is scheduled to be removed in Gradle 3.0"
My task build will build the artifact and then generate the POM and move the artifact to different location but I am getting below error.
My full script is
apply plugin: 'cpp'
apply plugin: 'java'
//-- set the group for publishing
group = 'com.tr.anal'
/**
* Initializing GAVC settings
*/
def buildProperties = new Properties()
file("version.properties").withInputStream {
stream -> buildProperties.load(stream)
}
//add the jenkins build version to the version
def env = System.getenv()
if (env["BUILD_NUMBER"]) buildProperties.analBuildVersion += "_${env["BUILD_NUMBER"]}"
version = buildProperties.analBuildVersion
println "${version}"
//name is set in the settings.gradle file
group = "com.t.anal"
version = buildProperties.analBuildVersion
println "Building ${project.group}:${project.name}:${project.version}"
repositories {
maven {
url "http://cm.thon.com:900000/artifactory/libs-snapshot-local"
}
maven {
url "http://cm.thon.com:9000000/artifactory/libs-release"
}
}
dependencies {
compile ([
"com.tr.anal:analytics-engine-common:4.+"
])
}
model {
repositories {
libs(PrebuiltLibraries) {
jdk {
headers.srcDirs "${System.properties['java.home']}/../include",
"${System.properties['java.home']}/../include/win32",
"${System.properties['java.home']}/../include/darwin",
"${System.properties['java.home']}/../include/linux"
}
}
}
}
model {
platforms {
x64 { architecture "x86_64" }
x86 { architecture "x86" }
}
}
model {
components {
main(NativeLibrarySpec) {
sources {
cpp {
source {
lib library: 'main', linkage: 'static'
lib library: 'jdk', linkage: 'api'
srcDir "src/main/c++/native"
include "**/JniSupport.cpp"
include "**/DiseaseStagingJni.cpp"
}
}
}
}
}
}
def nativeHeadersDir = file("$buildDir/nativeHeaders")
//def compilePath = configurations.compile.resolve().collect {it.absolutePath}.join(";")
binaries.all {
// Define toolchain-specific compiler and linker options
if (toolChain in Gcc) {
cppCompiler.args "-I${nativeHeadersDir}"
cppCompiler.args "-g"
linker.args '-Xlinker', '-shared -LNativeJNI/src/main/resources/DSresources/DSLib -lds64 -Wl'
}
}
//def nativeHeadersDir = file("$buildDir/nativeHeaders")
task nativeHeaders {
// def nativeHeadersDir = file("$buildDir/nativeHeaders")
def outputFile = file("$nativeHeadersDir/DiseaseStagingJniWrapper.h")
def classes = [
'com.truvenhealth.analyticsengine.common.diseasestaging.DiseaseStagingJniWrapper'
]
inputs.files sourceSets.main.output
inputs.property('classes', classes)
outputs.file outputFile
doLast {
outputFile.parentFile.mkdirs()
def compilePath = configurations.compile.resolve().collect {it.absolutePath}.join(":")
println "Using Compile Path: ${compilePath}"
exec {
executable org.gradle.internal.jvm.Jvm.current().getExecutable('javah')
args '-o', outputFile
args '-classpath', compilePath
args classes
}
}
}
tasks.withType(CppCompile) { task ->
task.dependsOn nativeHeaders
}
/*****************************
* Packaging
*****************************/
apply plugin: "maven"
// Workaround for Jenkins-Artifactory plugin not picking up the POM file
def pomFile = file("${buildDir}/libs/${archivesBaseName.toLowerCase()}-${version}.pom")
task newPom << {
pom {
project {
groupId project.group
artifactId project.name
version project.version
description = "Configuration Management Gradle Plugin"
}
}.writeTo(pomFile)
}
//disabling the install task since we're not using maven for real
install.enabled = false
//for publishing to artifactory via jenkins
if(project.hasProperty('artifactoryPublish')) {
artifactoryPublish {
mavenDescriptor pomFile
}
}
def filechange = file("build/libs/NativeJNI-${project.version}.so")
task copyfile(type: Copy) {
from 'build/binaries/mainSharedLibrary'
into 'build/libs'
include('libmain.so')
rename ('libmain.so', "$filechange")
}
//build.dependsOn copyfile
task build (dependsOn: ["newPom","copyfile"]) << {
println "build in progress"
}
def someFile = file("build/libs/NativeJNI-${project.version}.so")
artifacts {
archives someFile
}
Looks like this was a bug in 3.0,
https://github.com/GradleFx/GradleFx/issues/235

Specify war in gradle's tomcatRunWar

I'm playing with the tomcat plugin for gradle and in my build/tmp/tomcatRun/work/Tomcat/localhost/myWebApp directory its empty. Is there a way for me to specify the location of my war to deploy?
I tried
[tomcatRun, tomcatRunWar]*.destinationDir= new File("$buildDir/libs").getAbsoluteFile().getPath()
and
[tomcatRun, tomcatRunWar]*.warDirectory= new File("$buildDir/libs").getAbsoluteFile().getPath()
Update
I've added the build scripts below. When I run my new tasks I've been running
gradle build integrationTest
Here is a snippet from the parent build.gradle:
buildscript {
repositories {
add(new org.apache.ivy.plugins.resolver.URLResolver()) {
name = 'GitHub'
addArtifactPattern 'http://cloud.github.com/downloads/[organisation]/[module]/[module]-[revision].[ext]'
}
}
dependencies {
classpath 'bmuschko:gradle-tomcat-plugin:0.9.2'
}
}
allprojects {
apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "idea"
ext.springVersion = "3.1.1.RELEASE"
ext.hibernateVersion = "3.6.7.Final"
ext.mysqlVersion = "5.1.20"
ext.tomcatVersion = "7.0.26"
ext.junitVersion = "4.10"
ext.httpClientVersion = "4.2"
ext.pdfboxVersion = "1.7.1"
ext.resxWebserviceVersion = "10.4.2"
loadConfiguration()
}
and my webapps build.gradle:
apply plugin: "maven"
apply plugin: "war"
apply plugin: "tomcat"
def now = new Date()
def cssDir = new File("truexpense-web/src/main/webapp/css").getAbsoluteFile().getPath()
def minCssName = 'all-min.css'
def jsDir = new File("truexpense-web/src/main/webapp/js").getAbsoluteFile().getPath()
def minJsName = 'all-min.js'
ext.requestor = ''
ext.fromAddress = ''
ext.replyAddress = ''
ext.formattedDate = now.format('dd MMM yyy HH:mm')
ext.product = 'Truexpense'
configurations {
deployerJars
jasper
mail
}
dependencies {
//Compile time but not included dependencies
providedCompile "javax.servlet:javax.servlet-api:3.0.1"
providedCompile "org.apache.tomcat:tomcat-jdbc:$tomcatVersion"
//Compile time dependencies
compile project(":truexpense-domain")
compile project(":truexpense-repository")
compile project(":truexpense-service")
compile "org.springframework:spring-core:$springVersion"
compile "org.springframework:spring-web:$springVersion"
compile "org.hibernate:hibernate-core:$hibernateVersion"
compile "org.hibernate:hibernate-envers:$hibernateVersion"
compile "org.hibernate:hibernate-ehcache:$hibernateVersion"
compile "org.hibernate:hibernate-validator:4.2.0.Final"
compile "commons-io:commons-io:2.3"
compile "commons-codec:commons-codec:1.6"
compile "org.springframework.security:spring-security-core:3.1.0.RELEASE"
compile "org.springframework.security:spring-security-config:3.1.0.RELEASE"
compile "org.springframework.security:spring-security-web:3.1.0.RELEASE"
compile "javax.mail:mail:1.4"
compile "mysql:mysql-connector-java:$mysqlVersion"
compile "com.google.visualization:visualization-datasource:1.0.2"
compile "org.ostermiller:utils:1.07.00"
compile "net.sf.ofx4j:ofx4j:1.4"
compile "org.jpedal:jbig2:1"
compile "org.apache.pdfbox:txp-fontbox:$pdfboxVersion"
compile "org.apache.pdfbox:txp-jempbox:$pdfboxVersion"
compile "org.apache.pdfbox:txp-pdfbox:$pdfboxVersion"
compile "taglibs:taglibs-unstandard:1"
compile "org.codehaus.jackson:jackson-mapper-asl:1.9.7"
compile "org.apache.httpcomponents:httpclient:$httpClientVersion"
//Runtime only dependencies
runtime "commons-beanutils:commons-beanutils-core:1.8.3"
runtime "joda-time:joda-time:2.1"
runtime "org.springframework.security:spring-security-taglibs:3.1.0.RELEASE"
runtime "org.springframework:spring-beans:$springVersion"
runtime "org.springframework:spring-context:$springVersion"
runtime "org.springframework:spring-core:$springVersion"
runtime "org.springframework:spring-expression:$springVersion"
runtime "org.springframework:spring-instrument:$springVersion"
runtime "org.springframework:spring-instrument-tomcat:$springVersion"
runtime "org.springframework:spring-jdbc:$springVersion"
runtime "org.springframework:spring-jms:$springVersion"
runtime "org.springframework:spring-orm:$springVersion"
runtime "org.springframework:spring-oxm:$springVersion"
runtime "org.springframework:spring-tx:$springVersion"
runtime "org.springframework:spring-web:$springVersion"
runtime "org.springframework:spring-webmvc:$springVersion"
runtime ("commons-fileupload:commons-fileupload:1.2.2") {
exclude group: "javax.servlet", module: "javax.servlet-api"
exclude group: "portlet-api"
}
runtime ("javax.servlet:jstl:1.2") {
exclude group: "javax.servlet", module: "javax.servlet-api"
exclude group: "javax.servlet", module: "jsp-api"
}
//Test only dependencies
tomcat "org.apache.tomcat:tomcat-dbcp:${tomcatVersion}"
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
}
//Deployments
deployerJars "org.apache.maven.wagon:wagon-http:1.0-beta-2"
[tomcatRun, tomcatRunWar]*.httpPort = 8090
[tomcatRun, tomcatStop]*.stopPort = 8081
[tomcatRun, tomcatStop]*.stopKey = 'stopKey'
task integrationTest(type: Test) {
include '**/*IntegrationTest.*'
doFirst {
tomcatRun.daemon = true
tomcatRun.execute()
}
doLast {
tomcatStop.execute()
}
}
test {
exclude '**/*IntegrationTest.*'
}
}
war {
baseName='truexpense'
eachFile {
if (it.name == 'login_css_include.jsp') {
it.expand(loginCSS: "login-min.css?t=${now.getTime()}")
}
else if (it.name == 'all_css_include.jsp') {
it.expand(allCSS: "all-min.css?t=${now.getTime()}")
}
else if (it.name == 'all_js_include.jsp') {
it.expand(allJS: "all-min.js?t=${now.getTime()}")
}
}
}
task deploy << { deploy() }
task minifyCSS << {
def files = fileTree(dir: "${cssDir}", includes: [
"analysis.css",
"header.css",
"footer.css",
"blocks.css",
"chosen.css",
"grids.css",
"space.css",
"dataTables.css",
"newCore.css",
"core.css",
"skin_clean.css",
"plugins.css",
"css3.css",
"jquery-ui.css",
"jquery.lightbox-0.5.css",
"jqueryFileTree.css",
"jquery.qtip.css",
"expense.css",
"report.css",
"zentab.css"
]).getFiles().sort({it.name})
concatenate("${cssDir}/all.css", files)
yuiCompressor("${cssDir}/all.css", "${cssDir}/${minCssName}")
yuiCompressor("${cssDir}/login.css", "${cssDir}/login-min.css")
}
task minifyJS << {
def files = fileTree(dir: "${jsDir}", excludes:[
'all*.js',
'jqtouch*.js'
]).getFiles().sort({it.name})
concatenate("${jsDir}/all.js", files)
yuiCompressor("${jsDir}/all.js", "${jsDir}/${minJsName}")
}
def yuiCompressor(from, to) {
ant.java(jar:"tools/yuicompressor-2.4.7.jar", fork: true, failonerror: true) {
arg(value: from)
arg(value: "-o")
arg(value: to)
}
}
def concatenate(filePath, files) {
File file = new File(filePath)
if (file.exists()) {
file.write("")
}
files.each { File f ->
file.append(f.getText() + '\n')
}
}
def deploy() {
println "Deleting ${tomcatHome}/webapps/${war.baseName}"
delete "${tomcatHome}/webapps/${war.baseName}"
println "Deleting ${tomcatHome}/work/Catalina/localhost/${war.baseName}"
delete "${tomcatHome}/work/Catalina/localhost/${war.baseName}"
println "Copying ${war.archiveName} to ${tomcatHome}/webapps"
copy {
from war.archivePath
into "${tomcatHome}/webapps"
}
}
How do you reference your applicationContext.xml in your web.xml? If you use the full path (/WEB-INF/classes/applicationContext.xml) then I'd probably change it to search for it on the classpath:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

Resources