How to enforce a java compiler version with gradle? - java

In all of my projects, I use gradle and specify the following:
sourceCompatibility = "1.7"; // for example
targetCompatibility = "1.7"; // defaults to sourceCompatibility
Now, I have three different versions of the JDK installed, from 1.6 to 1.8. In order to switch from one version to another, I source shell files to change PATH, JAVA_HOME and even JDK_HOME.
By accident it can happen that I use the wrong JDK version and I don't want that... Is there a possibility to check that the compiler version is equal to targetCompatibility before attempting any compilation task?

Answer to self, and thanks to #JBNizet for providing the initial solution...
The solution is indeed to use JavaVersion, and it happens that both sourceCompatibility and targetCompatibility accept a JavaVersion as an argument...
Therefore the build file has become this:
def javaVersion = JavaVersion.VERSION_1_7;
sourceCompatibility = javaVersion;
targetCompatibility = javaVersion; // defaults to sourceCompatibility
And then the task:
task enforceVersion << {
def foundVersion = JavaVersion.current();
if (foundVersion != javaVersion)
throw new IllegalStateException("Wrong Java version; required is "
+ javaVersion + ", but found " + foundVersion);
}
compileJava.dependsOn(enforceVersion);
And it works:
$ ./gradlew clean compileJava
:clean UP-TO-DATE
:enforceVersion FAILED
FAILURE: Build failed with an exception.
* Where:
Build file '/home/fge/src/perso/grappa-tracer-backport/build.gradle' line: 55
* What went wrong:
Execution failed for task ':enforceVersion'.
> Wrong Java version; required is 1.7, but found 1.8

I use the following:
task checkJavaVersion << {
if (!JavaVersion.current().isJava6()) {
String message = "ERROR: Java 1.6 required but " +
JavaVersion.current() +
" found. Change your JAVA_HOME environment variable.";
throw new IllegalStateException(message);
}
}
compileJava.dependsOn checkJavaVersion

If you want the version to be checked for all tasks, you can add an assertion in build.gradle to enforce it:
assert JavaVersion.current().isJava9Compatible(): "Java 9 or newer is required"
With Gradle 5.4.1, the failure looks like this:
$ ./gradlew --quiet build
FAILURE: Build failed with an exception.
* Where:
Build file '/home/codehearts/build.gradle' line: 15
* What went wrong:
A problem occurred evaluating root project 'Codehearts'.
> Java 9 or newer is required. Expression: org.gradle.api.JavaVersion.current().isJava9Compatible()
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 3s
You can also check exact versions if needed:
assert JavaVersion.current().isJava9(): "Java 9 is required"

Related

GraalVM "Invalid GAV coordinates" error? (Spring boot 3)

Recently I downloaded Spring Boot 3 to test the embedded GraalVM. I run the `./gradlew native compile command the result is:
$ ./gradlew nativeCompile
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':nativeCompile'.
> Invalid GAV coordinates: groovy:it_groovy_comparre: (expected format: groupId:artifactId: version)
....
BUILD FAILED in 752ms
What is my problem with dependencies? When I run that command in debug mode there is nothing new except this error.
NOTE:
my $JAVA_HOME variable value is: /home/<my username>/.jdks/graalvm-ce-java17-22.3.0/, which point to a Graalvm java
my build automation tool is Gradle.
When I tested the command in groovy the result was the same
I found the solution.
Firstly I added a version to my build.gradle file like this :
plugins {
// ...
}
group = 'groovy'
version = '1' // <-------------- HERE
sourceCompatibility = '17'
configurations {
//...
}
Just before executing the command ./gradlew nativeCompile, I ran the following two commands :
$ ./gradlew processAot
...
$ ./gradlew processTestAot
...
After that, everything works fine.

* What went wrong: Task 'bootJar' not found in project ':app-cloud-config-server'. * Try: Run gradlew tasks to get a list of available tasks

This is my first question on stack overflow.
So I am trying to run the build my springboot application app-cloud-config-server on my local system.
I ran this cd /app; ./gradlew app-cloud-config-server:build command on the terminal and got the below error:
What went wrong: Task 'bootJar' not found in project ':app-cloud-config-server'. * Try: Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
I checked multiple threads for the solution to this error based on which I tried
Including this in my build.gradle file to find the missing bootJar task
bootJar {
mainClassName = 'foxtrot.infra.applications.cloudconfig.CloudConfigServerApplication'
baseName = 'spring-boot-integration-test'
version = '0.1.0'
}
Couldn't resolve
Applied the below plugins
plugins {
id 'org.springframework.boot' version '2.2.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
Did gradle clean and followed the same steps
still couldn't resolve the issue.
What am I missing here?

Could not find method outputDir() on cucumber Java source of type org.gradle.api.internal.file.DefaultSourceDirectorySet

I am not able to run the cucumber task for the "com.github.samueltbrown.cucumber" plugin.
I get the following error:
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/freid/app/build.gradle' line: 118
* What went wrong:
A problem occurred evaluating root project 'app'.
> Could not find method outputDir() for arguments [/Users/freid/app/src/cucumber/java] on cucumber Java source of type org.gradle.api.internal.file.DefaultSourceDirectorySet.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
Here is my build.gradle file:
buildscript {
ext {
springBootVersion='2.2.4.RELEASE'
lombokVersion='1.18.4'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
plugins {
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'java'
id 'com.github.psxpaul.execfork' version '0.1.8'
id "com.jfrog.artifactory" version "4.7.2"
id "com.github.samueltbrown.cucumber" version "0.9"
}
dependencies {
testCompile 'info.cukes:cucumber-java:1.2.4'
}
sourceSets {
cucumber {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/cucumber/java')
}
resources.srcDir file('src/cucumber/resources')
}
}
cucumber {
formats = ['html:build/reports/html', 'json:build/reports/cucumber.json']
jvmOptions {
environment 'tag', System.getProperty("tag")
environment 'cucumber.local.server', 'localhost'
}
}
Given that the plugin com.github.samueltbrown.cucumber version 0.9 was released in 2015 and you are trying to run with a recent Spring Boot version, I would assume you are using a recent Gradle version as well.
So I believe you are hitting an incompatibility between the plugin and the Gradle version. Most likely an API changed and what the plugin does internally no longer works.
[/Users/freid/app/src/cucumber/java] looks like the toString of a collection of files, while SourceDirectorySet.outputDir only accepts a single File. So my guess is that the API of what returns the value that is used changed from a single file to a file collection at some point.

Android studio beginner :( Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0

Hi, Im new to coding and android studio. I wrote just a simple PSVM SOUT message and the code is correct but this is what it shows in my terminal (BTW this is a fresh new install) :
Initialization script 'C:\Users\Dom\AppData\Local\Temp\MainActivity_main__.gradle' line: 20
* What went wrong:
A problem occurred configuring project ':app'.
> Could not create task ':app:MainActivity.main()'.
> SourceSet with name 'main' not found.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more
log
output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
The gradle file that it is referring to looks like this:
def gradlePath = ':app'
def runAppTaskName = 'MainActivity.main()'
def mainClass = 'com.example.myapplication.MainActivity'
def javaExePath = 'S:/Program files (x86)/androidStudio/jre/bin/java.exe'
def _workingDir = 'C:/Users/Dom/AndroidStudioProjects/MyApplication'
def sourceSetName = 'main'
def javaModuleName = null
allprojects {
afterEvaluate { project ->
if(project.path == gradlePath && project?.convention?.findPlugin(JavaPluginConvention)) {
project.tasks.create(name: runAppTaskName, overwrite: true, type: JavaExec) {
if (javaExePath) executable = javaExePath
classpath = project.sourceSets[sourceSetName].runtimeClasspath
main = mainClass
if(_workingDir) workingDir = _workingDir
standardInput = System.in
if(javaModuleName) {
inputs.property('moduleName', javaModuleName)
doFirst {
jvmArgs += [
'--module-path', classpath.asPath,
'--module', javaModuleName + '/' + mainClass
]
classpath = files()
}
}
}
}
}
}
I have tried to update the gradle version but when I updated it to 6 it said it wasn't compatible with gradle 7. It says to run with --stacktrace option but what is it referring to?
where do I run this line of code?
You telling gradle to use the sourceset main which is normaly default, but do you really have a folder called main ?
I would expect you have this kind of folder ?
C:/Users/Dom/AndroidStudioProjects/MyApplication/src/main
Which version of Java do you use ?

grgit NoClassDefFoundError

Gradle throws a NoClassDefFoundError when trying to execute a grgit task.
Start of build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'org.ajoberstar:gradle-git:1.2.0'
}
}
apply plugin: 'com.android.application'
//
//
import org.ajoberstar.grgit.*
task clone << {
File dir = new File('contrib/otherstuff')
if(!dir.exists()) {
def grgit = Grgit.clone(dir: dir, uri: 'https://github.com/someguy/otherstuff.git')
}
// TODO else (pull)
}
project.afterEvaluate {
preBuild.dependsOn clone
}
// rest omitted
Output:
Relying on packaging to define the extension of the main artifact has been deprecated and is scheduled to be removed in Gradle 2.0
:src:myproject:clone FAILED
FAILURE: Build failed with an exception.
* Where:
Build file '/home/me/src/myproject/build.gradle' line: 20
* What went wrong:
Execution failed for task ':src:myproject:clone'.
> java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 16.937 secs
Line 20 is the call to Grgit.clone().
Do I need to add groovy as a build dependency (which the error message seems to indicate)? How and where would I add it?
EDIT: gradle version is 1.10, if it matters.
As #user149408 pointed out the Gradle version (v1.10 vs v2.10) mismatch, I dug a little bit further:
gradle-git-plugin commit for v0.7.0 specifies the Gradle version used (v1.11), so the build with v1.10 works fine.
Because the Gradle plugin always built with compile localGroovy() and compile gradleApi() which comes from Gradle, then if it builds with Gradle 2.x, it would incur the Groovy mismatch error.
What went wrong: Execution failed for task ':src:myproject:clone'.
java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling
In fact, the combo of Gradle v2.10 and gradle-git v1.2.0 just works fine.
Some sample build.gradle similar structure as in the question.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.ajoberstar:gradle-git:1.2.0'
}
}
import org.ajoberstar.grgit.*
task clone << {
File dir = new File('contrib/gs-spring-boot')
if(!dir.exists()) {
def grgit = Grgit.clone(dir: dir, uri: 'https://github.com/chenrui333/gs-spring-boot.git')
}
// TODO else (pull)
}
./gradlew clone would give you:
$ ls contrib/gs-spring-boot/
CONTRIBUTING.adoc LICENSE.code.txt LICENSE.writing.txt README.adoc complete initial test
Hope it helps!
I’ve managed to solve it.
grgit-1.2.0 appears to depend on groovy. Adding a classpath entry for groovy in the buildscript/dependencies block resulted in a different error:
Relying on packaging to define the extension of the main artifact has been deprecated and is scheduled to be removed in Gradle 2.0
:src:myproject:clone FAILED
FAILURE: Build failed with an exception.
* Where:
Build file '/home/me/src/myproject/build.gradle' line: 23
* What went wrong:
Execution failed for task ':src:myproject:clone'.
> java.lang.IncompatibleClassChangeError: the number of constructors during runtime and compile time for org.ajoberstar.grgit.auth.AuthConfig$Option do not match. Expected -1 but got 2
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 12.295 secs
Further research revealed that this might stem from a version incompatibility (as I’m stuck with Gradle 1.10 for other reasons).
Eventually I solved it by going back to grgit-0.7.0. Now my git task works and the repo gets cloned.

Categories