Gradle powermock codecoverage missed - gradle

How to configure gradle to produce code coverage for sonar when i'm using powermock in my tests? I found that jacoco don't support that. Is there any other codecoverage plugin to work with powermock?

Jacoco Offline Instrumentation is the solution for this.
see my gradle build file
Build and run tests:
Linux:
\$ ./gradlew
Windows:
\$ gradlew
------------------------------------------
"""
apply plugin: 'java'
apply plugin: 'org.sonarqube'
apply plugin: 'jacoco'
// Project group and version
group 'com.abcd.jacocoTest'
version '1.0.0'
// JDK version source compatibility
sourceCompatibility = 1.8
// JDK version target compatibility
targetCompatibility = 1.8
configurations {
jacocoAnt
jacocoRuntime
}
task wrapper(type: Wrapper) {
gradleVersion = "4.5.1"
}
defaultTasks 'clean', 'test'
buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.6.2"
}
}
repositories {
mavenCentral()
}
dependencies {
jacocoAnt group: 'org.jacoco', name: 'org.jacoco.ant', version: '0.8.1'
jacocoAgent group: 'org.jacoco', name: 'org.jacoco.agent', version: '0.8.1'
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.8.9'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.4'
testCompile group: 'org.powermock', name: 'powermock-api-mockito2', version: '1.7.4'
testCompile group: 'org.powermock', name: 'powermock-api-easymock', version: '1.7.4'
}
test {
testLogging {
afterSuite { desc, result ->
if (!desc.parent) { // will match the outermost suite
println "Unit Tests: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
}
}
}
jacoco {
append = "false"
destinationFile = file("$buildDir/reports/jacoco/jacoco-sonar/jacoco-coverage.exec")
}
}
jacoco {
toolVersion = "0.8.0"
}
jacocoTestReport {
reports {
html.destination file("${buildDir}/reports/jacoco/jacocoHtml")
}
}
sonarqube {
properties {
property "sonar.projectName", 'JacocoTest'
property "sonar.host.url", "http://localhost:9000"
property "sonar.java.binaries", "${buildDir}/classes"
property "sonar.java.libraries", "**/*.jar"
property "sonar.dynamicAnalysis", "reuseReports"
property "sonar.jacoco.reportPaths", "${buildDir}/reports/jacoco/jacoco-sonar/jacoco-coverage.exec"
}
}
task instrument(dependsOn: ['classes']) {
ext.outputDir = buildDir.path + '/reports/classes-instrumented'
doLast {
ant.taskdef(name: 'instrument',
classname: 'org.jacoco.ant.InstrumentTask',
classpath: configurations.jacocoAnt.asPath)
ant.instrument(destdir: outputDir) {
fileset(dir: sourceSets.main.output.classesDir)
}
}
}
gradle.taskGraph.whenReady { graph ->
if (graph.hasTask(instrument)) {
tasks.withType(Test) {
doFirst {
classpath = files(instrument.outputDir) + classpath + configurations.jacocoRuntime
}
}
}
}
task report(dependsOn: ['instrument', 'test']) {
doLast {
ant.taskdef(name: 'report',
classname: 'org.jacoco.ant.ReportTask',
classpath: configurations.jacocoAnt.asPath)
ant.report() {
executiondata {
ant.file(file: buildDir.path + '/reports/jacoco/jacoco-sonar/jacoco-coverage.exec')
}
structure(name: 'Example') {
classfiles {
fileset(dir: sourceSets.main.output.classesDir)
}
sourcefiles {
fileset(dir: 'src/main/java')
}
}
html(destdir: buildDir.path + '/reports/jacoco')
}
}
}
Here report task will create the offline instrumentation files of the project.
Finally, execute sonarqube task.
Then you can see the coverage of the powermocked classes also has included.
Execution command ./gradlew report sonarqube
Then go and see in your sonarqube host (localhost:9000).

You could try to use JaCoCo offline instrumentation instead of on-the-fly instrumentation as documented at https://github.com/powermock/powermock/wiki/Code-coverage-with-JaCoCo as long as https://github.com/powermock/powermock/issues/727 is not fixed which would make PowerMock compatible with JaCoCo on-the-fly instrumentation.
Alternatively you could use a different mocking framework, like e. g. JMockit. This is compatible with JaCoCo on-the-fly instrumentation as far as I remember.

I resigned to use gradle and jacoco. Now i'm using maven + cobertura + powermock and everything works without hacks. Why i'm using maven? Because i can't find how to produce xml code coverage report in cobertura using gradle.

Related

Gitlab CI failure with JHipster

I can build my JHipster gateway with gradle from the development machine, but when I give it to the Gitlab CI I get this error at the 'gradle-package' step:
92 $ ./gradlew bootJar -Pprod -x check --no-daemon
93 To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon: https://docs.gradle.org/6.4.1/userguide/gradle_daemon.html.
94 Daemon will be stopped at the end of the build stopping after processing
95 > Task :bootBuildInfo
96 > Task :nodeSetup SKIPPED
97 > Task :npmSetup SKIPPED
98 > Task :npmInstall UP-TO-DATE
99 > Task :webpack FAILED
100 FAILURE: Build failed with an exception.
101 * What went wrong:
102 Execution failed for task ':webpack'.
103 > A problem occurred starting process 'command 'npm''
This is the .gitlab-ci.yml
cache:
key: "$CI_COMMIT_REF_NAME"
paths:
- .gradle/
stages:
- check
- build
- test
- analyze
- package
- release
- deploy
before_script:
- export NG_CLI_ANALYTICS="false"
- export GRADLE_USER_HOME=`pwd`/.gradle
- ./gradlew npm_install -PnodeInstall --no-daemon
nohttp:
stage: check
script:
- ./gradlew checkstyleNohttp --no-daemon
gradle-compile:
stage: build
script:
- ./gradlew compileJava -x check -PnodeInstall --no-daemon
artifacts:
paths:
- build/classes/
- build/generated/
expire_in: 1 day
gradle-test:
stage: test
script:
- ./gradlew test -PnodeInstall --no-daemon
artifacts:
reports:
junit: build/test-results/test/TEST-*.xml
paths:
- build/test-results/
- build/jacoco/
expire_in: 1 day
gradle-integration-test:
stage: test
script:
- ./gradlew integrationTest -PnodeInstall --no-daemon
artifacts:
reports:
junit: build/test-results/integrationTest/TEST-*.xml
paths:
- build/test-results/
- build/jacoco/
expire_in: 1 day
frontend-test:
stage: test
script:
- ./gradlew npm_run_test -PnodeInstall --no-daemon
artifacts:
reports:
junit: build/test-results/TESTS-results-jest.xml
paths:
- build/test-results/
- build/jacoco/
expire_in: 1 day
gradle-package:
stage: package
script:
- ./gradlew bootJar -Pprod -x check --no-daemon
artifacts:
paths:
- build/libs/*.jar
- build/classes
expire_in: 1 day
# Uncomment the following line to use gitlabs container registry. You need to adapt the REGISTRY_URL in case you are not using gitlab.com
docker-push:
stage: release
variables:
REGISTRY_URL: 10.1.10.58
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHA
dependencies:
- gradle-package
script:
- ./gradlew jib -Pprod -Djib.allowInsecureRegistries=true -Djib.to.image=$IMAGE_TAG -Djib.to.auth.username="gitlab-ci-token" -Djib.to.auth.password=$CI_BUILD_TOKEN
build.gradle
buildscript {
repositories {
mavenLocal()
mavenCentral()
gradlePluginPortal()
maven { url "https://repo.spring.io/plugins-release" }
}
dependencies {
//jhipster-needle-gradle-buildscript-dependency - JHipster will add additional gradle build script plugins here
}
}
plugins {
id "java"
id "maven-publish"
id "idea"
id "jacoco"
id "org.springframework.boot"
id "com.google.cloud.tools.jib"
id "com.gorylenko.gradle-git-properties"
id "com.github.node-gradle.node"
id "net.ltgt.apt-eclipse"
id "net.ltgt.apt-idea"
id "net.ltgt.apt"
id "org.liquibase.gradle"
id "org.sonarqube"
id "io.spring.nohttp"
//jhipster-needle-gradle-plugins - JHipster will add additional gradle plugins here
}
group = "com.rps.png"
version = "0.0.1-SNAPSHOT"
description = ""
sourceCompatibility=1.8
targetCompatibility=1.8
assert System.properties["java.specification.version"] == "1.8" || "11" || "12" || "13" || "14"
apply from: "gradle/docker.gradle"
apply from: "gradle/sonar.gradle"
//jhipster-needle-gradle-apply-from - JHipster will add additional gradle scripts to be applied here
if (project.hasProperty("prod") || project.hasProperty("gae")) {
apply from: "gradle/profile_prod.gradle"
} else {
apply from: "gradle/profile_dev.gradle"
}
if (project.hasProperty("war")) {
apply from: "gradle/war.gradle"
}
if (project.hasProperty("gae")) {
apply plugin: 'maven'
apply plugin: 'org.springframework.boot.experimental.thin-launcher'
apply plugin: 'io.spring.dependency-management'
dependencyManagement {
imports {
mavenBom "io.github.jhipster:jhipster-dependencies:${jhipster_dependencies_version}"
}
}
appengineStage.dependsOn thinResolve
}
if (project.hasProperty("zipkin")) {
apply from: "gradle/zipkin.gradle"
}
idea {
module {
excludeDirs += files("node_modules")
}
}
eclipse {
sourceSets {
main {
java {
srcDirs += ["build/generated/sources/annotationProcessor/java/main"]
}
}
}
}
defaultTasks "bootRun"
springBoot {
mainClassName = "com.rps.png.GatewayuApp"
}
test {
useJUnitPlatform()
exclude "**/*IT*", "**/*IntTest*"
testLogging {
events 'FAILED', 'SKIPPED'
}
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
task integrationTest(type: Test) {
useJUnitPlatform()
description = "Execute integration tests."
group = "verification"
include "**/*IT*", "**/*IntTest*"
testLogging {
events 'FAILED', 'SKIPPED'
}
if (project.hasProperty('testcontainers')) {
environment 'spring.profiles.active', 'testcontainers'
}
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
check.dependsOn integrationTest
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests")
reportOn test
}
task integrationTestReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests")
reportOn integrationTest
}
if (!project.hasProperty("runList")) {
project.ext.runList = "main"
}
project.ext.diffChangelogFile = "src/main/resources/config/liquibase/changelog/" + new Date().format("yyyyMMddHHmmss") + "_changelog.xml"
liquibase {
activities {
main {
driver "org.h2.Driver"
url "jdbc:h2:file:./build/h2db/db/gatewayu"
username "gatewayu"
password ""
changeLogFile "src/main/resources/config/liquibase/master.xml"
defaultSchemaName ""
logLevel "debug"
classpath "src/main/resources/"
}
diffLog {
driver "org.h2.Driver"
url "jdbc:h2:file:./build/h2db/db/gatewayu"
username "gatewayu"
password ""
changeLogFile project.ext.diffChangelogFile
referenceUrl "hibernate:spring:com.rps.png.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
defaultSchemaName ""
logLevel "debug"
classpath "$buildDir/classes/java/main"
}
}
runList = project.ext.runList
}
gitProperties {
failOnNoGitDirectory = false
keys = ["git.branch", "git.commit.id.abbrev", "git.commit.id.describe"]
}
checkstyle {
toolVersion '${checkstyle_version}'
configFile file("checkstyle.xml")
checkstyleTest.enabled = false
}
nohttp {
source.include "build.gradle", "README.md"
}
configurations {
providedRuntime
implementation.exclude module: "spring-boot-starter-tomcat"
all {
resolutionStrategy {
// Inherited version from Spring Boot can't be used because of regressions:
// To be removed as soon as spring-boot use the same version
force 'org.liquibase:liquibase-core:3.9.0'
}
}
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
//jhipster-needle-gradle-repositories - JHipster will add additional repositories
}
dependencies {
// import JHipster dependencies BOM
if (!project.hasProperty("gae")) {
implementation platform("io.github.jhipster:jhipster-dependencies:${jhipster_dependencies_version}")
}
// Use ", version: jhipster_dependencies_version, changing: true" if you want
// to use a SNAPSHOT release instead of a stable release
implementation group: "io.github.jhipster", name: "jhipster-framework"
implementation "javax.annotation:javax.annotation-api"
implementation "org.springframework.boot:spring-boot-starter-cache"
implementation "io.dropwizard.metrics:metrics-core"
implementation "io.micrometer:micrometer-registry-prometheus"
implementation "net.logstash.logback:logstash-logback-encoder"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
implementation "com.fasterxml.jackson.module:jackson-module-jaxb-annotations"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
implementation "com.fasterxml.jackson.core:jackson-annotations"
implementation "com.fasterxml.jackson.core:jackson-databind"
implementation "com.fasterxml.jackson.module:jackson-module-afterburner"
implementation "org.apache.httpcomponents:httpclient"
implementation "javax.cache:cache-api"
implementation "org.hibernate:hibernate-core"
implementation "com.zaxxer:HikariCP"
implementation "commons-codec:commons-codec"
implementation "org.apache.commons:commons-lang3"
implementation "commons-io:commons-io"
implementation "javax.transaction:javax.transaction-api"
implementation "org.ehcache:ehcache"
implementation "org.hibernate:hibernate-jcache"
implementation "org.hibernate:hibernate-entitymanager"
implementation "org.hibernate.validator:hibernate-validator"
implementation "org.liquibase:liquibase-core"
liquibaseRuntime "org.liquibase:liquibase-core"
liquibaseRuntime "org.liquibase.ext:liquibase-hibernate5:${liquibase_hibernate5_version}"
liquibaseRuntime sourceSets.main.compileClasspath
implementation "org.springframework.boot:spring-boot-loader-tools"
implementation "org.springframework.boot:spring-boot-starter-mail"
implementation "org.springframework.boot:spring-boot-starter-logging"
implementation "org.springframework.boot:spring-boot-starter-actuator"
implementation "org.springframework.boot:spring-boot-starter-aop"
implementation "org.springframework.boot:spring-boot-starter-data-jpa"
testImplementation "org.testcontainers:mysql"
implementation "org.springframework.boot:spring-boot-starter-security"
implementation ("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
implementation "org.springframework.boot:spring-boot-starter-undertow"
implementation "org.springframework.boot:spring-boot-starter-thymeleaf"
implementation "org.zalando:problem-spring-web"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-zuul"
implementation "com.github.vladimir-bukhtoyarov:bucket4j-core"
implementation "com.github.vladimir-bukhtoyarov:bucket4j-jcache"
implementation "org.springframework.cloud:spring-cloud-starter"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-ribbon"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-hystrix"
implementation "org.springframework.retry:spring-retry"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client"
implementation "org.springframework.cloud:spring-cloud-starter-config"
implementation "org.springframework.cloud:spring-cloud-starter-security"
implementation "org.springframework.cloud:spring-cloud-starter-openfeign"
implementation "org.springframework.boot:spring-boot-starter-cloud-connectors"
implementation "org.springframework.security:spring-security-config"
implementation "org.springframework.security:spring-security-data"
implementation "org.springframework.security:spring-security-web"
implementation "org.springframework.security.oauth:spring-security-oauth2"
implementation "org.springframework.security:spring-security-jwt"
implementation "org.glassfish.jaxb:jaxb-runtime:${jaxb_runtime_version}"
implementation ("io.springfox:springfox-swagger2") {
exclude module: "mapstruct"
}
implementation "io.springfox:springfox-bean-validators"
implementation "mysql:mysql-connector-java"
liquibaseRuntime "mysql:mysql-connector-java"
implementation "org.mapstruct:mapstruct:${mapstruct_version}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstruct_version}"
annotationProcessor "org.hibernate:hibernate-jpamodelgen:${hibernate_version}"
annotationProcessor "org.glassfish.jaxb:jaxb-runtime:${jaxb_runtime_version}"
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:${spring_boot_version}"
testImplementation ("org.springframework.boot:spring-boot-starter-test") {
exclude group: "org.junit.vintage", module: "junit-vintage-engine"
}
testImplementation "org.springframework.security:spring-security-test"
testImplementation "org.springframework.boot:spring-boot-test"
testImplementation "com.tngtech.archunit:archunit-junit5-api:${archunit_junit5_version}"
testRuntimeOnly "com.tngtech.archunit:archunit-junit5-engine:${archunit_junit5_version}"
testImplementation "com.h2database:h2"
liquibaseRuntime "com.h2database:h2"
//jhipster-needle-gradle-dependency - JHipster will add additional dependencies here
}
if (project.hasProperty("gae")) {
task createPom {
def basePath = 'build/resources/main/META-INF/maven'
doLast {
pom {
withXml(dependencyManagement.pomConfigurer)
}.writeTo("${basePath}/${project.group}/${project.name}/pom.xml")
}
}
bootJar.dependsOn = [createPom]
}
task cleanResources(type: Delete) {
delete "build/resources"
}
wrapper {
gradleVersion = "6.4.1"
}
if (project.hasProperty("nodeInstall")) {
node {
version = "${node_version}"
npmVersion = "${npm_version}"
yarnVersion = "${yarn_version}"
download = true
}
}
compileJava.dependsOn processResources
processResources.dependsOn bootBuildInfo
This is a JHipster gateway 6.9 with only minor changes from the default. In particular, I didnt' touch the 'gradle-package' which is failing on the Gitlab Runner.
What's the [Docker] image you run your job on? I don't see any image: specifications in your .gitlab-ci.yml. Make sure it has npm installed or make sure that your Gradle scripts contains instructions or tasks for installing it. You should probably set nodeInstall property before running the build:
if (project.hasProperty("nodeInstall")) {
node {
version = "${node_version}"
npmVersion = "${npm_version}"
yarnVersion = "${yarn_version}"
download = true
}
}

Why SpotBugs Gradle plugin always generate XML report instead of HTML?

I am using Gradle 5.2, spotbugs-gradle-plugin version 2.0.0 and tried to generate SpotBugs report on my project. I used the following configuration on my project but it always create XML reports instead of html report.
buildscript {
repositories {
jcenter()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:+'
classpath "gradle.plugin.com.github.spotbugs:spotbugs-gradle-plugin:2.0.0"
}
}
allprojects {
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'com.github.spotbugs'
group = 'com.myproject'
version = '1.0.0'
repositories {
mavenCentral()
}
dependencies {
compile('com.google.cloud:google-cloud-storage:+') {
exclude group: "com.google.guava", module: "guava"
}
compile group: 'org.apache.commons', name: 'commons-collections4', version: '+'
compile group: 'com.google.guava', name: 'guava', version: '+'
testImplementation('org.junit.jupiter:junit-jupiter:+')
}
test {
useJUnitPlatform()
testLogging {
events "passed", "skipped", "failed"
}
}
}
project(':myproject') {
dependencies {
compile group: 'com.github.javafaker', name: 'javafaker', version: '+'
compile group: 'org.jsonschema2pojo', name: 'jsonschema2pojo-core', version: '+'
compile group: 'commons-lang', name: 'commons-lang', version: '+'
compile group: 'org.mongodb', name: 'bson', version: '+'
}
}
tasks.withType(JavaCompile) {
options.compilerArgs << '-Xlint:unchecked'
options.deprecation = true
}
spotbugsMain {
reports {
xml.enabled = false
html.enabled = true
}
}
What I did wrong here?
Kindly provide your inputs to create HTML report instead of XML!

Gradle Plugin Execution Order

I have written this gradle file
group 'com.abhi'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'org.flywaydb.flyway'
sourceCompatibility = 1.8
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.flywaydb:flyway-gradle-plugin:3.2.1'
classpath 'org.jooq:jooq-codegen:3.7.1'
classpath 'com.h2database:h2:1.4.177'
}
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.jooq', name: 'jooq', version: '3.7.1'
compile group: 'org.jooq', name: 'jooq-meta', version: '3.7.1'
compile group: 'org.jooq', name: 'jooq-codegen', version: '3.7.1'
runtime group: 'com.h2database', name: 'h2', version: '1.4.177'
}
flyway {
url = 'jdbc:h2:file:target/foobar'
user = 'sa'
}
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)
.configuration('xmlns': 'http://www.jooq.org/xsd/jooq-codegen-3.7.0.xsd') {
jdbc() {
driver('org.h2.Driver')
url('dbc:h2:file:target/foobar')
user('sa')
password('')
}
generator() {
database() {
}
generate() {
}
target() {
packageName('com.abhi.jooq.models')
directory('src/main/java')
}
}
}
// Run the code generator
// ----------------------
org.jooq.util.GenerationTool.generate(
javax.xml.bind.JAXB.unmarshal(new StringReader(writer.toString()), org.jooq.util.jaxb.Configuration.class)
)
when I say gradle compile it throws an exception
Could not load schemata
java.lang.NullPointerException
at org.jooq.impl.MetaImpl.meta(MetaImpl.java:120)
at org.jooq.impl.MetaImpl.getCatalogs(MetaImpl.java:143)
at org.jooq.impl.MetaImpl.getSchemas(MetaImpl.java:168)
at org.jooq.util.jdbc.JDBCDatabase.getSchemasFromMeta(JDBCDatabase.java:135)
at org.jooq.util.jdbc.JDBCDatabase.getSchemata0(JDBCDatabase.java:124)
at org.jooq.util.AbstractDatabase.getSchemata(AbstractDatabase.java:279)
I think the problem is that the code at the bottom of the script executes much before the "flyway" plugin.
Is there a way I can ensure that the code below is executed only after the flyway plugin has executed?
Yes, if you suppose, the problem is in execution order, then you can modify it, just like with any other tasks. Take a look at the documentation of the flyway plugin. According to it, this plugin adds some extra tasks to your build script, for thos one tasks are: flywayMigrate, flywayClean etc. You can make any of your tasks depending (with dependsOn option) on the tasks form this plugin and make them running just after the plugin's job is done.

Setting up Gradle Cargo

I am trying follow this tutorial to set up Grails/ Cargo: https://github.com/bmuschko/gradle-cargo-plugin I wish to use this plugin to deploy wars to local tomcat instances and to start and stop them.
Here is my build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'cargo'
sourceCompatibility = 1.5
version = '1.0'
jar {
manifest {
attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version
}
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
testCompile group: 'junit', name: 'junit', version: '4.+'
classpath 'org.gradle.api.plugins:gradle-cargo-plugin:0.6.1'
def cargoVersion = '1.3.3'
cargo "org.codehaus.cargo:cargo-core-uberjar:$cargoVersion",
"org.codehaus.cargo:cargo-ant:$cargoVersion"
}
cargo {
containerId = 'tomcat6x'
port = 9090
deployable {
file = file('/Users/me/Documents/gradlemucks/grails_2/hello-world/target/hello-world-0.1.war')
context = 'helloworld'
}
local {
homeDir = file('/Users/me/developer/servers/apache-tomcat-6.0.37')
output = file('build/output.log')
tomcat {
ajpPort = 9091
}
}
}
test {
systemProperties 'property': 'value'
}
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}
When I do gradle tasks in the terminal I get:
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/me/Documents/workspaces/regress_test/httptests/build.gradle' line: 3
* What went wrong:
A problem occurred evaluating root project 'httptests'.
> Plugin with id 'cargo' not found.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
What are my doing wrong?
The buildscript itself need the cargo dependency so adding:
buildscript {
repositories {
mavenCentral()
}
dependencies { classpath "org.gradle.api.plugins:gradle-cargo-plugin:0.6" }
}
should make it able to find the cargo plugin.

tasks.setupAll.dependsOn(copyJars) does not work in gradle?

I tried following the answer here
how to override a task making it depend on one of mine in gradle
but it fails with
Could not find property 'setupAll' on task set.
I have tried a few things
Make the task in subprojects section depend on master:copyJars but that fails
The below solution
stripped off the tasks which didn't work.
I have only ONE build.gradle file and the settings.gradle file. The settings gradle file is
include 'master', 'toneserver','webserver'
The master build.gradle file is(SPECIFICALLY, search for the two instances of setupAll as somehow there is something wrong with that)
//NOTE: Currently this file is for dependency management only but we would like
// to convert all of the build to gradle from the ant files. We needed to add dependency
// management so did so with gradle first as a first step in the process of evolution
allprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
buildDir = 'output'
task hello << { task -> println "I'm $task.project.name" }
build << { task -> println "MASTER: I'm building now classpath=$sourceSets.main.compileClasspath.files" }
}
project(':toneserver') {
dependencies {
compile fileTree(dir: 'play-1.2.4/framework/lib', include: '*.jar')
compile fileTree(dir: 'play-1.2.4/framework', include: '*.jar')
compile project(':master')
compile project(':webserver')
}
task eclipse(overwrite: true) {
}
}
project(':webserver') {
dependencies {
compile fileTree(dir: 'play-1.2.4/framework/lib', include: '*.jar')
compile fileTree(dir: 'play-1.2.4/framework', include: '*.jar')
compile project(':master')
}
//playframework has it's own generation of .classpath and .project fils so do not
//overwrite their versions
task eclipse(overwrite: true) {
}
}
project(':master') {
project.ext.genLibDir = file('lib')
project.ext.fixedLibDir = file('libother')
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '4.1.4.Final'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.6.6'
compile group: 'org.slf4j', name: 'log4j-over-slf4j', version: '1.6.6'
compile group: 'ch.qos.logback', name: 'logback-core', version: '1.0.6'
compile group: 'joda-time', name: 'joda-time', version: '2.1'
compile group: 'com.google.inject',name: 'guice', version: '3.0'
compile group: 'com.google.protobuf',name: 'protobuf-java', version: '2.4.1'
//to be erased soon
compile group: 'commons-configuration',name:'commons-configuration',version: '1.8'
compile group: 'org.jboss.netty', name: 'netty', version: '3.2.7.Final'
//compile group: 'org.asteriskjava',name: 'asterisk-java', version: '1.0.0.M3'
compile fileTree(dir: project.ext.fixedLibDir, include: '*.jar')
}
task('copyJars') {
ext.collection = files { genLibDir.listFiles() }
delete ext.collection
copy { from configurations.compile into genLibDir }
copy { from fixedLibDir into genLibDir }
}
tasks.setupAll.dependsOn(copyJars)
}
subprojects {
version = 'Developer-Build'
//configurations.compile {
// exclude group: 'javax.jms', module: 'jms'
// exclude group: 'com.sun.jdmk', module: 'jmxtools'
// exclude group: 'com.sun.jmx', module: 'jmxri'
//}
task('setupAll', dependsOn: ['eclipse']) {
description = 'Update jars from remote repositories and then fix eclipse classpath for master project'
}
hello << {println "- I depend on stserver"}
build << { println "subproject:source sets=$sourceSets.main.java.srcDirs" }
}
task release << { println "putting together release" }
//TODO: have a release task AND if version is null when running the release task
//throw an exception telling the user to pass in a version with "./build -Dversion=xxxx"
//The automated build will call the release task with a version number like that
gradle.taskGraph.whenReady {taskGraph ->
if (taskGraph.hasTask(release) && version == 'Developer-Build') {
throw new StopExecutionException("You must specify -Dversion=<some version> to run the release task")
} else {
version = '1.0-SNAPSHOT'
}
}
What is going on with this? Overriding tasks to depend on other stuff should work pretty easily I though(maybe that syntax is still wrong?)
thanks,
Dean
never mind, stupid mistake, forgot my task was in subprojects and should be outside and needed a : as well so new setupAll is outside subprojects and is
task('setupAll', dependsOn: [':master:copyJars', 'eclipse']) {
description = 'Update jars from remote repositories and then fix eclipse classpath for master project'
}

Resources