How to execute custom gradle task for debugging from IDE (Netbeans) - gradle

We are using custom source set and hence the default gradle tasks "run" and "debug" cant be used from netBeans to launch.
Please let me know the steps to configure Netbeans such that when I clik "Debug Project", I need to execute custom gradle task :-
gradle -PmainClass=xxx.TestDelMe execute
Sample build.gradle with execute task :-
sourceSets {
integTest{
java.srcDir 'src/integTest/java'
resources.srcDir 'src/integTest/resources'
}
}
/**
* This task creates the jar for the compiled test code.
*/
task integTestJar (type: Jar) {
from sourceSets.integTest.output
appendix = 'integ-tests'
}
/*
gradle -PmainClass=xxx.TestDelMe execute
*/
task execute(type:JavaExec) {
main = mainClass
debug = true
dependsOn 'assemble', 'integTestJar'
classpath = sourceSets.integTest.runtimeClasspath + sourceSets.integTest.compileClasspath
}
Thanks,
Subra

Found below workaround :-
Enable debugging for JavaExec type task by using the flag "debug=true" (as below)
/*
gradle -PmainClass=xxx.TestDelMe execute
*/
task execute(type:JavaExec) {
main = mainClass
**debug = true**
dependsOn 'assemble', 'integTestJar'
classpath = sourceSets.integTest.runtimeClasspath + sourceSets.integTest.compileClasspath
}
Create a custom task for execute from
Launch the custom task by right clicking the project
Now the JVM will wait on port 5005 till netbeans attaches to it as below
Then setbreak point and enjoy debugging

Related

gradle : How to run externalNativeBuildDebug task after a custom task

I am working on Android project which uses build.gradle. I want to run externalNativeBuildDebug task after a custom task.
In build.gradle, I specify:
task mytask()
{
println 'hello'
}
tasks.getByName("externalNativeBuildDebug").mustRunAfter(mytask)
But gradle throws this error :
Task with name 'externalNativeBuildDebug' not found in project ':app'.
I have defined externalNativeBuild block in android{} block
externalNativeBuild {
cmake {
path file('CMakeLists.txt')
version '3.18.1'
}
}
Is there a way to get externalNativeBuildDebug task and set its dependency?

How can I get Gradle to build dependencies before running my task?

Background: I am trying to hook the compiler for my own domain-specific language into Gradle. The DSL is compiled to Java source code, so I have built a task that runs before the Java compiler. The compiler cannot currently handle multiple projects with dependencies, so I'm trying to add that.
My DSL has packages like Java that get mapped to identical Java packages. The same should be true for projects. In that case, for each project, the DSL sources get compiled to Java source code, as well as meta-data (a JSON file per compiled class, containing information from the DSL's type system that cannot be mapped to Java types). When project A depends on B, the DSL compilation process for A needs the meta-data files from B. That meta-data should be packaged as resources into the JAR file together with the generated and compiled Java code, as well as possibly hand-written and compiled Java code.
FoobarPlugin.groovy:
class FoobarPlugin implements Plugin<Project> {
#Override
void apply(Project project) {
// create the compileFoobar task
CompileFoobarTask task = project.getTasks().create('compileFoobar', CompileFoobarTask.class);
task.group = 'build';
task.setDescription('Compiles Foobar to Java code.');
task.sourceDirectory = new File(project.projectDir, "src/main/foobar");
task.outputDirectory = new File(project.getBuildDir(), "foobar-java");
// compileFoobar must run before compiling Java code
project.tasks.compileJava.dependsOn(task);
// add the task's output folders as Java source folders
project.sourceSets.main.java.srcDirs += task.outputDirectory;
project.sourceSets.main.resources.srcDirs += task.outputDirectory;
project.sourceSets.test.java.srcDirs += task.outputDirectory;
project.sourceSets.test.resources.srcDirs += task.outputDirectory;
// Turn project dependencies into task dependencies. We have to delay this until the end of the configuration
// phase because project dependencies are not fully known until then.
project.gradle.addBuildListener(new BuildAdapter() {
#Override
void projectsEvaluated(Gradle gradle) {
project.configurations.compile.each {
task.dependencyOutputs += it
}
}
});
}
}
CompileFoobarTask.groovy:
class CompileFoobarTask extends DefaultTask {
#InputDirectory
File sourceDirectory;
#InputFiles
List<File> dependencyOutputs = new ArrayList<>();
#OutputDirectory
File outputDirectory;
#TaskAction
void run() {
FileUtils.write(new File(outputDirectory, "timestamp"), "" + System.currentTimeMillis(), StandardCharsets.UTF_8);
}
}
build.gradle from project A:
apply plugin: 'java'
apply plugin: foobar.gradle.FoobarPlugin
repositories {
mavenCentral()
}
dependencies {
compile project(':b')
}
build.gradle from project B:
apply plugin: 'java'
apply plugin: foobar.gradle.FoobarPlugin
repositories {
mavenCentral()
}
dependencies {
compile 'org.apache.commons:commons-lang3:3.0'
}
Test runs and output:
martin#xyz:~/git-repos/gradle-test$ ./gradlew clean a:compileFoobar
adding dependency /home/martin/git-repos/gradle-test/b/build/libs/b.jar to task task ':a:compileFoobar'
> Task :a:compileFoobar
running task ':a:compileFoobar'
BUILD SUCCESSFUL in 1s
4 actionable tasks: 2 executed, 2 up-to-date
martin#xyz:~/git-repos/gradle-test$ ./gradlew clean b:compileFoobar
adding dependency /home/martin/git-repos/gradle-test/b/build/libs/b.jar to task task ':a:compileFoobar'
> Task :b:compileFoobar
running task ':b:compileFoobar'
BUILD SUCCESSFUL in 469ms
4 actionable tasks: 2 executed, 2 up-to-date
martin#xyz:~/git-repos/gradle-test$ ./gradlew clean a:compileJava
adding dependency /home/martin/git-repos/gradle-test/b/build/libs/b.jar to task task ':a:compileFoobar'
> Task :a:compileFoobar
running task ':a:compileFoobar'
> Task :b:compileFoobar
running task ':b:compileFoobar'
BUILD SUCCESSFUL in 487ms
7 actionable tasks: 5 executed, 2 up-to-date
martin#xyz:~/git-repos/gradle-test$ ./gradlew clean b:compileJava
adding dependency /home/martin/git-repos/gradle-test/b/build/libs/b.jar to task task ':a:compileFoobar'
> Task :b:compileFoobar
running task ':b:compileFoobar'
BUILD SUCCESSFUL in 471ms
4 actionable tasks: 3 executed, 1 up-to-date
As you can see, even though I add b.jar as a dependency to a:compileFoobar, Gradle won't build that JAR before running a:compileFoobar. The Java plugin seems to do something different because running a:compileJava WILL build b.jar first. What do I have to do to achieve the same for my task?
What you need to do is to explicitly create a Task dependency between consumer project's compileFoobar task and the producer project's jar task (in your example where project a depends on project b, you need to create task dependency a:compileFoobar -> b.jar)
You can achieve this in your custom plugin, by checking if the current project has dependencies of type ProjectDependency: if so you create the task dependency accordingly.
Code sample (in your plugin apply() method):
// Turn project dependencies into task dependencies. We have to delay this until the end of the configuration
// phase because project dependencies are not fully known until then.
project.gradle.addBuildListener(new BuildAdapter() {
#Override
void projectsEvaluated(Gradle gradle) {
project.configurations.each { config ->
config.dependencies.each { dep ->
if (dep instanceof ProjectDependency) {
def producerProject = ((ProjectDependency) dep).dependencyProject
def producerJarTask = producerProject.tasks.jar
println " **** Project $project.name depends on $producerProject.name"
println " => create dependency between $task to $producerJarTask"
task.dependsOn(producerJarTask)
}
}
}
}
})
Build execution:
$ ./gradlew clean a:compileFoobar
**** Project a depends on b
=> create dependency between task ':a:compileFoobar' to task ':b:jar'
> Task :a:clean
> Task :b:clean
> Task :b:compileFoobar
> Task :b:compileJava NO-SOURCE
> Task :b:processResources NO-SOURCE
> Task :b:classes UP-TO-DATE
> Task :b:jar
> Task :a:compileFoobar

Exclude a module or dir or subtask from gradle configuration and execution

I have a task with name test and code is as below :
tasks {
"test"(Test::class) {
useJUnitPlatform {
excludeTags = setOf("e2e", "integration")
}
}
When execute this task with gradle command ./gradlew test --info, gradle is scanning all the modules of my project and generating a configuration with has some tasks from module named data-export-ui-kjs.
I want gradle to exclude the tasks from data-export-ui-kjs module while configuring & executing test task. I have used below code to achieve this but its not successful
gradle.taskGraph.whenReady {
TaskExecutionGraphListener { graph ->
if(it.name.contains("data-export-ui-kjs")) {
it.enabled = false
}
}
}
Kindly help me to get this done. Thanks in advance
Working as expected. Modified the code. Its syntax issue itseems

How to apply javaagent to gretty plugin based on gradle command line?

The question is specific, but it's more of a general 'how to do this in gradle' question.
I have a demo java web app that I can run using the gretty plugin. I would like to selectively control whether a javaagent is applied to the jvmArgs of the gretty process based on a command line flag. The agent jar location is known by getting its path from a dummy configuration:
configurations {
agent
}
dependencies {
...
agent group: 'com.foo', name: 'foo-agent', version: '1.0'
}
I know I can access the jar file location using something like:
project.configurations.agent.find { it.name.startsWith("foo-agent") }
How can I selectively apply that to the gretty jvmArgs configuration based on a command line property such as
gradle -PenableAgent
I ended up solving this by creating a task and simply calling it before I run the war:
task agent {
doFirst {
def agentJar = project.configurations.agent.find { it.name.startsWith("foo-agent") }
gretty.jvmArgs << "-javaagent:" + agentJar
}
}
Then I can simply call:
gradle agent appRunWar
In my project I use Spring Instrument as java agent so this was my solution.
You can make appRun task dependent on agent task then no additional gradle run parameter needed.
dependencies {
...
agent 'org.springframework:spring-instrument:4.2.4.RELEASE'
}
configurations {
dev
agent
}
gretty {
...
contextPath = '/'
jvmArgs=[]
springBoot = true
...
}
task agent {
doFirst {
def agentJar = project.configurations.agent.find{it.name.contains("spring-instrument") }
gretty.jvmArgs << "-javaagent:" + agentJar
}
}
project.afterEvaluate {
tasks.appRun.dependsOn agent
}

How to run JBoss TattleTale from inside Gradle build

I am in love with JBoss TattleTale. Typically, in my Ant builds, I follow the docs to define the Tattletale tasks and then run them like so:
<taskdef name="report"
classname="org.jboss.tattletale.ant.ReportTask"
classpathref="tattletale.lib.path.id"/>
...
<tattletale:report source="${src.dir]" destination="${dest.dir}"/>
I am now converting my builds over to Gradle and am struggling to figure out how to get Tattletale running in Gradle. There doesn't appear to be a Gradle-Tattletale plugin, and I'm not experienced enough with Gradle to contribute one. But I also know that Gradle can run any Ant plugin and can also executing stuff from the system shell; I'm just not sure how to do this in Gradle because there aren't any docs on this (yet).
So I ask: How do I run the Tattletale ReportTask from inside a Gradle build?
Update
Here is what the Gradle/Ant docs show as an example:
task loadfile << {
def files = file('../antLoadfileResources').listFiles().sort()
files.each { File file ->
if (file.isFile()) {
ant.loadfile(srcFile: file, property: file.name)
println " *** $file.name ***"
println "${ant.properties[file.name]}"
}
}
}
However, no where in here do I see how/where to customize this for Tattletale and its ReportTask.
The following is adapted from https://github.com/roguePanda/tycho-gen/blob/master/build.gradle
It bypasses ant and directly invokes the Tattletale Java class.
It was changed to process a WAR, and mandates a newer javassist in order to handle Java 8 features such as lambdas.
configurations {
tattletale
}
configurations.tattletale {
resolutionStrategy {
force 'org.javassist:javassist:3.20.0-GA'
}
}
dependencies {
// other dependencies here...
tattletale "org.jboss.tattletale:tattletale:1.2.0.Beta2"
}
task createTattletaleProperties {
ext.props = [reports:"*", enableDot:"true"]
ext.destFile = new File(buildDir, "tattletale.properties")
inputs.properties props
outputs.file destFile
doLast {
def properties = new Properties()
properties.putAll(props)
destFile.withOutputStream { os ->
properties.store(os, null)
}
}
}
task tattletale(type: JavaExec, dependsOn: [createTattletaleProperties, war]) {
ext.outputDir = new File(buildDir, "reports/tattletale")
outputs.dir outputDir
inputs.files configurations.runtime.files
inputs.file war.archivePath
doFirst {
outputDir.mkdirs()
}
main = "org.jboss.tattletale.Main"
classpath = configurations.tattletale
systemProperties "jboss-tattletale.properties": createTattletaleProperties.destFile
args([configurations.runtime.files, war.archivePath].flatten().join("#"))
args outputDir
}
The previous answers either are incomplete or excessively complicated. What I did was use the ant task from gradle which works fine. Let's assume your tattletale jars are beneath rootDir/tools/...
ant.taskdef(name: "tattleTaleTask", classname: "org.jboss.tattletale.ant.ReportTask", classpath: "${rootDir}/tools/tattletale-1.1.2.Final/tattletale-ant.jar:${rootDir}/tools/tattletale-1.1.2.Final/tattletale.jar:${rootDir}/tools/tattletale-1.1.2.Final/javassist.jar")
sources = "./src:./src2:./etcetera"
ant.tattleTaleTask(
source: sources,
destination: "tattleTaleReport",
classloader: "org.jboss.tattletale.reporting.classloader.NoopClassLoaderStructure",
profiles: "java5, java6",
reports: "*",
excludes: "notthisjar.jar,notthisjareither.jar,etcetera.jar"
){
}
So the above code will generate the report beneath ./tattleTaleReport. It's that simple. The annoyance is that the source variable only accepts directories so if there are jars present in those directories you do not wish to scan you need to add them to the excludes parameter.

Resources