Delombok'ing source code with added jar dependencies - java

I am unable to delombok my Java source code, apparently due to jar dependencies that the project has, and I don't understand why. There are two jar files that have to be committed to the repo to tag along, and they are added to the project in the dependencies node of the build.gradle file by adding the line compile files('myproj1.jar'). So, the relevant part of the build.gradle file looks like this:
dependencies {
compile files('myproj1.jar')
compile files('myproj2.jar')
.....
}
When I run the delombok task I get the following error:
Execution failed for task ':delombok'.
> taskdef class lombok.delombok.ant.Tasks$Delombok cannot be found
using the classloader AntClassLoader[/path/to/repo/myproj1.jar:/path/to/repo/myproj2.jar]
Why would delombok task be using the AntClassLoader from the jar files?
I have tried the delombok'ing code from this post
Here is the task from my build.gradle file
def srcJava = 'src/main/java'
def srcDelomboked = 'build/src-delomboked'
task delombok {
// delombok task may depend on other projects already being compiled
dependsOn configurations.compile.getTaskDependencyFromProjectDependency(true, "compileJava")
// Set up incremental build, must be made in the configuration phase (not doLast)
inputs.files file(srcJava)
outputs.dir file(srcDelomboked)
doLast {
FileCollection collection = files(configurations.compile)
FileCollection sumTree = collection + fileTree(dir: 'bin')
ant.taskdef(name: 'delombok', classname: 'lombok.delombok.ant.Tasks$Delombok', classpath: configurations.compile.asPath)
ant.delombok(from:srcJava, to:srcDelomboked, classpath: sumTree.asPath)
}
}
I expect to be able to delombok my Java source code as part of the build process so that when the project is compiled there are no dependencies on Lombok.

So after continued trial an error, I have a working implementation. To answer my own question, the problem has nothing to do with the additional Jar files. Rather, when gradle runs the delombok task, the classes in the lombok jar are not in the classpath of the org.gradle.api.AntBuilder (ie, the ant task), and so it does not have a reference to lombok.delombok.ant.Tasks$Delombok anywhere (which seems obvious at this point, but not at the time).
The solution thus far has been to add those references in from configurations.compile
Combining code snippits from this post and this post you can do it with something like this:
def srcDelomboked = 'build/src-delomboked'
task delombok {
description 'Delomboks the entire source code tree'
def srcJava = 'src/main/java'
inputs.files files( srcJava )
outputs.dir file( srcDelomboked )
doFirst {
ClassLoader antClassLoader = org.apache.tools.ant.Project.class.classLoader
def collection = files( configurations.compile + configurations.testCompile )
def sumTree = collection + fileTree( dir: 'bin' )
sumTree.forEach { File file ->
antClassLoader.addURL(file.toURI().toURL())
}
ant.taskdef( name: 'delombok', classname: 'lombok.delombok.ant.Tasks$Delombok',
classpath: configurations.compile.asPath + configurations.testCompile.asPath )
ant.delombok( from: srcJava, to: srcDelomboked, classpath: sumTree.asPath )
}
}
sourceSets {
main {
java { srcDirs = [ srcDelomboked ] } //blow away the old source sets so that we only use the delomboked source sets
}
test {
java { srcDirs += [ srcDelomboked ] } //but add those new source sets to the tests so that their references are available at test time
}
}
compileJava.dependsOn(delombok)
bootJar {
mainClassName = 'com.myproj.MyMainClass' // you will need this if its a Spring Boot project
}
Hope this helps whomever else needs to delombok their code.

Related

How to provide generated data-binding classes in a Gradle Javadoc task?

With this Gradle task I've used to extract AAR, in order to generate Javadoc:
task javadoc(type: Javadoc) {
doFirst {
configurations.implementation.filter { it.name.endsWith('.aar') }.each { aar ->
copy {
from zipTree(aar)
include "**/classes.jar"
into "$buildDir/tmp/aarsToJars/${aar.name.replace('.aar', '')}/"
}
}
}
failOnError false
options.linkSource true
options.links("https://docs.oracle.com/en/java/javase/11/docs/api/")
options.links("https://developer.android.com/reference/")
title = "Colorpicker Library ${versionName} API"
source = android.sourceSets.main.java.srcDirs
classpath = files(new File("${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"))
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
classpath += fileTree(dir: "$buildDir/tmp/aarsToJars/")
configurations.implementation.setCanBeResolved(true)
classpath += configurations.implementation
destinationDir = file("${project.buildDir}/outputs/javadoc/")
exclude "**/BuildConfig.java"
exclude "**/R.java"
}
It fails since I've enabled androidx.databinding 7.2.1 inside the library module:
> Task :library:javadoc
...\ColorPickerDialogFragment.java:24: error: package com.acme.databinding does not exist
import com.acme.databinding.DialogColorPickerBinding;
^
...\ColorPickerDialogFragment.java:46: error: cannot find symbol
DialogColorPickerBinding mDataBinding;
^
symbol: class DialogColorPickerBinding
location: class ColorPickerDialogFragment
2 errors
How can I add these generated sources to classpath? Ignoring the class import doesn't seem to be an option. Or does javadoc have to depend on the task, which generates these (bad timing)? In general, exclude "**/ColorPickerDialogFragment.java" is not the answer I'm looking for.
Extracting the built AAR and putting it on classpath provides the generated classes -
but it's a whole lot more elegant to reference the intermediate classes.jar already:
task javadoc(type: Javadoc) {
...
doFirst {
...
def aar_main = new File("$buildDir/intermediates/aar_main_jar")
if (aar_main.exists()) {
copy {
from aar_main
include "**/classes.jar"
into "$buildDir/tmp/aarsToJars/aar_main_jar/"
}
}
}
}
One can also check .exists() before already:
javadoc.onlyIf {
new File("$buildDir/intermediates/aar_main_jar").exists()
}

Task in gradle to include java class before compile

I need to create Gradle task which can replace .java files before Gradle build.
Gradle build package app in .war file. And I need to have replaced bytecode there after build.
I tried sourceSets Gradle task but it can only exclude files.
sourceSets {
main {
java {
exclude 'com/myapp/example/resource/impl/ResourceBundleImpl.java'
}
}
}
But I need to also include file in the same place. How I can do it with Gradle?
The directory to file that I need to exclude: com/myapp/example/resource/impl/ResourceBundleImpl.java
The directory to file that I need to include: src/main/webapp/WEB-INF/my/ResourceBundleImpl.java
To copy file content it is also posible solution.But How can I do it before compile time?
The below task didn't helped, becouse in build file have .java files instead of .classe file.
task prepareSources(type: Copy) {
from('src/main/webapp/WEB-INF/my')
into('build/classes/java/main/com/myapp/example/resource/impl')com/myapp/example
}
// Prepare sources, before compile
compileJava {
dependsOn prepareSources
}
The below task throws :
Task :cdx-war:compileJava FAILED
error: package com.myapp.example.util does not exist
sourceSets {
main {
java {
srcDir "$projectDir"
exclude 'com/medtronic/diabetes/carelink/rbps/resource/impl/ResourceBundleImpl.java'
include 'src/main/webapp/WEB-INF/my/ResourceBundleImpl.java'
}
}
I put classes that I need to replace together and add suffix to one of them and replace this suffix during compile time :
sourceSets {
main {
java {
srcDirs = ["$buildDir\\generated-src"]
}
}
}
task copySourceSet(type: Copy) {
println 'Change java class in patient-svc-war'
from "$rootDir\\patient-svc-war\\src\\main\\java"
into "$buildDir\\generated-src"
from file("$rootDir\\patient-svc-war\\**_suffix.java")
into "$buildDir\\generated-src"
rename { String fileName ->
fileName.replace("_suffix", "")
}
filter { line -> line.replaceAll('_suffix', '')}
}
compileJava.source "$buildDir\\generated-src"
compileJava {
dependsOn copySourceSet
}
compileJava.doLast {
delete "$buildDir\\generated-src"
}

Gradle: Task with path not found in project

I have a gradle project with the following structure:
rootDir
|--agent-v1.0.0
|--agent.jar
|--proj1
|-- // other project files
|--build.gradle
|--proj2
|-- // other project files
|--build.gradle
|--build.gradle
I would like to run test.jvmArgs = ['javaagent:agent-v1.0.0/agent.jar'] for all subprojects, so I wrote the following task in the root build.gradle:
subprojects {
task cs {
outputs.upToDateWhen { false }
dependsOn test.jvmArgs = ['javaagent:../agent-v1.0.0/agent.jar']
}
}
But this fails with:
Could not determine the dependencies of task ':proj1'.
Task with path 'javaagent:../agent-v1.0.0/agent.jar' not found in project ':proj1'.
I've tried this by putting the agent-v1.0.0 in both the root, and in each project, and it still fails. What am I missing?
Why are you wrapping that logic in a new task? And then passing the return from jvmArgs to dependsOn?
Just configure the test tasks correctly:
subprojects {
tasks.withType(Test) {
jvmArgs "-javaagent:${project.rootDir}/agent-v1.0.0/agent.jar"
}
}
A task can depend on another task. So dependsOn expects a task as argument. test.jvmArgs = ['javaagent:../agent-v1.0.0/agent.jar'] is not a task.
If you want to configure all the test tasks of all subprojects to have additional jvm args, then the syntax would be
subprojects {
// this block of code runs for every subproject
afterEvaluate {
// this block of code runs after the subproject has been evaluated, and thus after
// the test task has been added by the subproject build script
test {
// this block of code is used to configure the test task of the subproject
// this configures the jvmArgs property of the test task
jvmArgs = ['javaagent:../agent-v1.0.0/agent.jar']
}
}
}
But just don't copy and paste this code. Read the grade user guide, and learn its fundamental concepts.

Gradle Include Source Files

I have a project in which I have two different 'sub-projects', the main library and a compiler for a programming language in a directory structure like this:
- build.gradle
- src
- library
- compiler
- ...
My build.gradle looks like this:
sourceSets
{
library
{
java
{
srcDir 'src/library'
srcDir 'src/asm'
}
}
compiler
{
java
{
srcDir 'src/compiler'
}
}
//...
}
// ...
task buildLib(type: Jar, dependsOn: 'classes') {
from sourceSets.library.output
classifier = 'dyvil-library'
}
task buildCompiler(type: Jar, dependsOn: 'classes') {
from sourceSets.compiler.output
classifier = 'dyvil-compiler'
}
My problem is that whenever I try to run the buildCompiler task, the build fails and the Java Compiler gives me hundreds of errors in places where the compiler source code references classes in the library. I already tried to make the compiler dependant on the library classes like this:
task buildCompiler(type: Jar, dependsOn: [ 'classes', 'libraryClasses' ]) {
from sourceSets.compiler.output
classifier = 'dyvil-compiler'
}
But that did not help. I know that I could theoretically copy the srcDirs from sourceSets.library into sourceSets.compiler like this:
compiler
{
java
{
srcDir 'src/library'
srcDir 'src/asm'
srcDir 'src/compiler'
}
}
But that seems like a bad idea for obvious reasons.
Is there another way to include the source files from the library when compiling the compiler (duh)?
There's a similar question on SO here.
I replicated your situation locally and the fix was to add a line to the sourceSets for compiler as follows:
compiler
{
java {
srcDir 'src/compiler'
}
compileClasspath += library.output
}

Gradle scala class already defined with combined Java compilation

I have the following scala compilation issue
scala -> depends upon java source
java source -> depends upon scala source
My scala code is in src/main/scala
My java code is in src/main/java
I cant change this code so I need to compile this with gradle and it currently compiles with JRuby just fine.
I have read the following posts on how to solve this issue:
http://forums.gradle.org/gradle/topics/how_to_compile_a_java_class_that_depends_on_a_scala_class_in_gradle
http://forums.gradle.org/gradle/topics/how_to_compile_a_java_class_that_depends_on_a_scala_class_in_gradle
I added this to my build:
ext {
baseName = 'd2'
description = 'Divisional IVR.'
combinedSources = "$buildDir/combined-sources"
}
apply plugin: 'scala'
compileScala.taskDependencies.values = compileScala.taskDependencies.values - 'compileJava'
compileJava.dependsOn compileScala
sourceSets.main.scala.srcDir "$combinedSources"
sourceSets.main.java.srcDirs = []
I tried to copy all the scala and java files to one location:
compileScala.dependsOn{
copyAllSourceFiles
}
task copyAllSourceFiles(type:Copy) {
description = 'Copy All Source Files.'
from('src/main/java') {}
from('/src/main/scala') {}
into combinedSources
includeEmptyDirs = false
}
But now I get an error:
[ant:scalac] Compiling 18 source files to C:\usr\git_workspaces\xivr\d2\target\classes\main
[ant:scalac] Compiling 18 scala and 196 java source files to C:\usr\git_workspaces\xivr\d2\target\classes\main
[ant:scalac] C:\usr\git_workspaces\xivr\d2\target\combined-sources\com\comcast\ivr\d2\actors\AlternateAniWithAccountActor.scala:9: error: AlternateAniWithAccountActor is already defined as class AlternateAniWithAccountActor
It almsot seems like scalaCompile sees $combinedSources and 'src/main/scala'
It almsot seems like scalaCompile sees $combinedSources and 'src/main/scala'
That's how you configured it: src/main/scala is the default, and you added "$combinedSources". To override the default, use sourceSets.main.scala.srcDirs = [combinedSources].
In any case, you don't have to (and shouldn't) copy sources around. Here is one solution that neither requires copying nor reconfiguring of task dependencies:
sourceSets.main.scala.srcDir "src/main/java"
sourceSets.main.java.srcDirs = []
Now, your Java and Scala code will get joint-compiled, and can depend on each other arbitrarily.
PS: Instead of "$combinedSources", use combinedSources.
gradle.properties
theVersion=2.1
theSourceCompatibility=1.7
theScalaVersion=2.10.3
build.gradle
apply {
plugin 'scala'
plugin 'java'
plugin 'idea'
}
ext {
scalaVersion = theScalaVersion
}
sourceCompatibility = theSourceCompatibility
tasks.withType(ScalaCompile) {
scalaCompileOptions.useAnt = false
}
dependencies {
compile "org.scala-lang:scala-library:$theScalaVersion"
compile "org.scala-lang:scala-compiler:$theScalaVersion"
}
sourceSets {
main.scala.srcDirs = ["src/main/scala", "src/main/java"]
main.java.srcDirs = []
}

Categories

Resources