Unsupported java version 61 with Blockhound && CloseableHttpClient | -AllowRedefinitionToAddDeleteMethods - java

At the start of the application I am spotting three warnings:
Java HotSpot(TM) 64-Bit Server VM warning: Option AllowRedefinitionToAddDeleteMethods was deprecated in version 13.0 and will likely be removed in a future release.
Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
But its only warning. Unfortunately I am getting errors aswell:
ERROR i.o.javaagent.tooling.HelperInjector - Error preparing helpers while processing class org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter for spring-webflux. Failed to inject helper classes into instance org.springframework.boot.loader.LaunchedURLClassLoader#64b31700
java.lang.UnsupportedOperationException: Cannot get defined package using reflection: Unsupported class file major version 61
OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
2022-02-25 12:30:22.226Z ERROR i.o.javaagent.tooling.HelperInjector - Error preparing helpers while processing class reactor.blockhound.shaded.net.bytebuddy.dynamic.loading.InjectionClassLoader for classloader. Failed to inject helper classes into instance org.springframework.boot.loader.LaunchedURLClassLoader#bae47a0
java.lang.UnsupportedOperationException: Cannot get defined package using reflection: Unsupported class file major version 61
ERROR i.o.javaagent.tooling.HelperInjector - Error preparing helpers while processing class org.apache.http.impl.client.CloseableHttpClient for apache-httpclient. Failed to inject helper classes into instance org.springframework.boot.loader.LaunchedURLClassLoader#64b31700
java.lang.UnsupportedOperationException: Cannot get defined package using reflection: Unsupported class file major version 61
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Initializable$Unavailable.getDefinedPackage(ClassInjector.java:442)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.injectRaw(ClassInjector.java:218)
at io.opentelemetry.javaagent.tooling.HelperInjector.injectClassLoader(HelperInjector.java:205)
at io.opentelemetry.javaagent.tooling.HelperInjector.transform(HelperInjector.java:137)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.doTransform(AgentBuilder.java:10364)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:10302)
at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.access$1600
In the project I am using Azure KeyVault, and BlockHound to communicate with that.
Application.java
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
BlockHound
.builder()
.allowBlockingCallsInside(KeyVaultClient.class.getName(), "getSecret")
.allowBlockingCallsInside(ManagedIdentityCredential.class.getName(), "getToken")
.install();
SpringApplication.run(MyApplication.class, args);
}
}
I have added -XX:+AllowRedefinitionToAddDeleteMethods to the VM options in IntelliJ.
I have also added it to the gradle.build file, but it seems to not work properly.
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '2.5.10'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'pmd'
id 'checkstyle'
id 'com.github.spotbugs' version '4.7.2'
id 'com.github.ben-manes.versions' version '0.39.0'
id 'io.freefair.lombok' version '5.3.3.3'
id 'com.gorylenko.gradle-git-properties' version '2.3.1'
id 'com.coditory.integration-test' version '1.3.0'
}
apply from: 'gradle/jacoco.gradle'
apply from: 'gradle/spotbugs.gradle'
group = 'my.group'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
jar {
enabled = false
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
ext {
set('springCloudVersion', '2020.0.3')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom 'com.azure.spring:azure-spring-cloud-dependencies:2.13.0'
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.cloud:spring-cloud-starter'
implementation 'org.springframework.cloud:spring-cloud-starter-sleuth'
implementation 'org.zalando:logbook-spring-boot-starter:2.14.0'
implementation group: 'org.zalando', name: 'logbook-spring-boot-webflux-autoconfigure', version: '2.11.0'
implementation 'io.projectreactor.tools:blockhound:1.0.6.RELEASE'
implementation 'com.azure.spring:azure-spring-cloud-appconfiguration-config'
implementation 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok-mapstruct-binding:0.2.0'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'net.javacrumbs.json-unit:json-unit-assertj:2.28.0'
}
springBoot {
buildInfo()
}
lombok {
version = '1.18.20'
}
pmd {
toolVersion = '6.33.0'
ruleSets = []
ruleSetConfig = rootProject.resources.text.fromFile('config/pmd/ruleset.xml')
sourceSets = [sourceSets.main]
consoleOutput = true
ignoreFailures = true
}
checkstyle {
toolVersion = '8.41.1'
config = rootProject.resources.text.fromFile('config/checkstyle/checkstyle.xml')
showViolations = false
checkstyleTest.enabled = false
checkstyleIntegration.enabled = false
}
tasks.withType(Test) {
useJUnitPlatform()
testLogging {
events = ['passed', 'failed', 'skipped']
exceptionFormat = 'full'
}
// this one is needed for blockhound to work in tests
jvmArgs('-XX:+AllowRedefinitionToAddDeleteMethods')
}
bootRun {
// this one is needed for blockhound to work
jvmArgs('-XX:+AllowRedefinitionToAddDeleteMethods')
args = ['--spring.profiles.active=native']
}
docker.entrypoint:
#!/bin/bash
exec java -Djava.security.egd=file:/dev/./urandom \
-XX:+AllowRedefinitionToAddDeleteMethods \
-XX:+UseG1GC \
-XX:MaxRAMPercentage=70 \
-XX:+PrintFlagsFinal \
-XshowSettings:vm \
-javaagent:/opt/myapp/agent.jar \
-jar /opt/myapp/myapp.jar
I am using: Java 17.0.2 and gradle 7.3
I have already tried changing spring.profiles.active to native, local etc. I have also migrated project from Java 16 to 17, and from gradle 7.1 to 7.3, other dependencies aswell. I am having issues with springboot in version 2.6.4, but possibly I should raise cloud dependencies' versions, but not sure how are they compatible with each other.
The solution is working fine, I am obtaining properties from KeyVault as expected.
I want to get rid off those warnings, but I am out of ideas at the moment. Maybe somebody had similiar situation?

Related

How to configure kapt to generate Java17 Java stubs in Android Gradle build file

My current Android project is displaying the following build messages:-
> Task :shared:resource:kaptGenerateStubsProductionDebugKotlin
'compileProductionDebugJavaWithJavac' task (current target is 17) and 'kaptGenerateStubsProductionDebugKotlin' task (current target is 1.8) jvm target compatibility should be set to the same Java version.
By default will become an error since Gradle 8.0+! Read more: https://kotl.in/gradle/jvm/target-validation
Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain
How do you configure kapt to generate stubs in a specific version of java?
I have tried...
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KaptGenerateStubs).configureEach {
kotlinJavaToolchain.jdk.use(
"/usr/local/opt/openjdk#17/libexec/openjdk.jdk/Contents/Home",
JavaVersion.VERSION_17
)
}
and
kapt {
javacOptions {
option("--target", 17)
}
}
none of which made any difference
Is it possible to control the java version for stubs generated by kapt in an Android project?
Having enabled verbose logging in kapt3 I can now see I have configure target correctly
Javac options: {--target=17, --source=17}
and in addition
[INFO] All Javac options: {-Adagger.fastInit=enabled=-Adagger.fastInit=enabled, -Adagger.hilt.android.internal.disableAndroidSuperclassValidation=true=-Adagger.hilt.android.internal.disableAndroidSuperclassValidation=true, -Adagger.hilt.android.internal.projectType=LIBRARY=-Adagger.hilt.android.internal.projectType=LIBRARY, -ASomeKaptArgument=ArgumentValue=-ASomeKaptArgument=ArgumentValue, -Akapt.kotlin.generated=/Users/frank/github/mobile-android-practiceupdate/shared/resource/build/generated/source/kaptKotlin/productionDebug=-Akapt.kotlin.generated=/Users/frank/github/mobile-android-practiceupdate/shared/resource/build/generated/source/kaptKotlin/productionDebug, -Adagger.hilt.internal.useAggregatingRootProcessor=false=-Adagger.hilt.internal.useAggregatingRootProcessor=false, --target=17, --source=17, -proc:=only, accessInternalAPI=true,.....
however I still see the above build message
why is kapt ignoring my javacOptions?
To recreate this issue:-
Main project gradle
plugins {
id 'com.android.application' version '8.0.0-alpha11' apply false
id 'com.android.library' version '8.0.0-alpha11' apply false
id 'org.jetbrains.kotlin.android' version '1.8.0' apply false
id 'com.google.dagger.hilt.android' version '2.44.2' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
gradle wrapper
#Tue Oct 25 07:38:32 BST 2022
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Gradle JDK
then use kapt for say room or hilt in any app or sub module in your project with java version set to 17
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'dagger.hilt.android.plugin'
id "org.jetbrains.kotlin.kapt"
}
android {
kapt {
javacOptions {
option("--target", "17")
}
}
kotlinOptions {
jvmTarget = '17'
freeCompilerArgs += [
"-Xcontext-receivers",
"-opt-in=androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi",
"-opt-in=kotlinx.coroutines.ObsoleteCoroutinesApi"]
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
coreLibraryDesugaringEnabled true
}
namespace 'com.my.app'
compileSdk 33
buildToolsVersion "33.0.1"
defaultConfig {
applicationId "com.my.app"
minSdk 26
targetSdk 33
versionCode 3
versionName "3.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
flavorDimensions "default"
productFlavors {
development {
dimension "default"
}
staging {
dimension "default"
}
production {
dimension "default"
}
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.4.0-dev-k1.8.0-33c0ad36f83'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.0'
implementation 'org.conscrypt:conscrypt-android:2.5.2'
implementation 'com.google.dagger:hilt-android:2.44.2'
kapt 'com.google.dagger:hilt-android-compiler:2.44.2'
kapt 'androidx.hilt:hilt-compiler:1.0.0'
}
these are my gradle.properties
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx8192m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
kapt.verbose=true
# positive value will enable caching
# use the same value as the number of modules that use kapt
kapt.classloaders.cache.size=5
# disable for caching to work
kapt.include.compile.classpath=false
kapt.incremental.apt=false
the version of android studio is
Android Studio Flamingo | 2022.2.1 Canary 11
Build #AI-222.4459.24.2221.9445173, built on December 30, 2022
Runtime version: 17.0.4.1+0-17.0.4.1b469.62-9127311 x86_64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
macOS 12.6.1
GC: G1 Young Generation, G1 Old Generation
Memory: 4096M
Cores: 12
Metal Rendering is ON
Registry:
external.system.auto.import.disabled=true
ide.text.editor.with.preview.show.floating.toolbar=false
gradle.version.catalogs.dynamic.support=true
ide.images.show.chessboard=true
Non-Bundled Plugins:
com.android.aas (3.5.1)
com.jetbrains.kmm (0.5.1(222)-30)
I have created this bug report with attached example android project
UPDATE
by adding this to my project level build.gradle file the messages disappeared:-
subprojects {
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
kotlinOptions.jvmTarget = "17"
}
}
Repro
(note: the Google issuetracker doesn't allow downloading the ZIP, did you check some checkbox there to hide it? There's nothing secret in the zip 😉)
So, using the example provided in the semi-related Gradle issue I was able to reproduce with gradlew assemble.
Investigation
At this point I'm looking for how kapt task gets the Java version, because it should pick up kotlinOptions { jvmTarget = '17' } without question.
Source code
For this I'll need sources, which are not available when using .gradle files. Konversion of a build.gradle file is necessary so that Android Studio imports the JARs on the plugin classpath under "External Libraries > Kotlin Script dependencies". This means we can browse the sources of Kotlin, AGP, Gradle. So I changed the root build.gradle to build.gradle.kts (which imports all related plugins) so it reads:
plugins {
id("com.android.application") version "8.0.0-alpha11" apply false
id("org.jetbrains.kotlin.android") version "1.8.0" apply false
}
(Tip: one AGP plugin declaration is enough to lock in the version of all com.android.* plugins.)
Reading code
The problematic task is kaptGenerateStubsDebugKotlin, so the task class name should contain GenStub in it, and indeed there's org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask, which extends KotlinCompile, hello old friend! KaptGenerateStubsTask.setupCompilerArgs looks like a good place to start.
Debug setup
At this point it's easier to read the code while executing as well to see the values, so I started a debugging session:
gradlew cleanKaptGenerateStubsDebugKotlin assemble --no-daemon -Dorg.gradle.debug=true
Then in Android Studio > Run > Edit Configurations... > + > Remote JVM Debug (defaults are good) > OK. And then select the just-created "Unnamed" run config and press the green bug (Debug) button.
Debugging notes
Behavior of setupCompilerArgs:
contributeArguments does a lot of setup
args.jvmTarget is null initially
compilerOptions.jvmTarget.get() is 17 (compilerOptions in this case is kotlinc task)
(compilerOptions as KotlinJvmCompilerOptionsDefault).fillDefaultValues(args) clears args.jvmTarget (was already cleared)
compilerOptions.fillCompilerArguments(args) sets args.jvmTarget = compilerOptions.jvmTarget.orNull?.target (wohoo, we have 17!)
(compilerOptions as KotlinJvmCompilerOptionsDefault).fillCompilerArguments(args)
sets args.jvmTarget = compilerOptions.jvmTarget.orNull?.target (wtf, we are on null again)
Conclusion
So at this point we know that the problem is that Kapt's jvmTarget doesn't inherit from the global kotlinOptions, this sounds like a KGP bug that only manifests with different targets as in your repro.
I was curious where this is set, and searching for jvmTarget.set yielded AndroidProjectHandler which sounds pretty relevant. Looking at the calls to wireExtensionOptionsToCompilation they only set up the kotlinCompile, not the kapt task.
Workaround
Armed with this knowledge the only option I see is
// TODO remove this once https://youtrack.jetbrains.com/issue/KT-.... is fixed
tasks.withType(org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask).configureEach {
kotlinOptions.jvmTarget = '17'
}
(If you don't want to reference internal classes use the Kapt tasks's superclass KotlinCompile instead; that will configure more though, not just the problematic part.)
Report
Please report this to YouTrack! Only JetBrains is able to fix this at the moment. Sadly I don't have high hopes for a fix, because Google is in the process of taking over the Android part of KGP (early stages); fingers crossed they won't reimplement the same problem.
Fix
Following the suggestion from JetBrains, this will also solve the issue, however it forces users to use the same JDK and target bytecode version:
kotlin {
jvmToolchain(17)
}
Note
Kotlin 1.8 added new DSL for setting these things, but only to tasks, it's not supporting the module level yet, see https://kotlinlang.org/docs/whatsnew18.html#limitations and the big green note above that section.
I have updated my version Android Studio to
Android Studio Giraffe | 2022.3.1 Canary 1
Build #AI-223.4884.69.2231.9486165, built on January 13, 2023
Runtime version: 17.0.5+0-17.0.5b653.23-9410051 x86_64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
macOS 12.6.1
GC: G1 Young Generation, G1 Old Generation
Memory: 4096M
Cores: 12
Metal Rendering is ON
Registry:
external.system.auto.import.disabled=true
ide.text.editor.with.preview.show.floating.toolbar=false
ide.images.show.chessboard=true
Non-Bundled Plugins:
com.android.aas (3.5.1)
and upgraded to gradle
plugins {
id 'com.android.application' version '8.1.0-alpha01' apply false
id 'com.android.library' version '8.1.0-alpha01' apply false
id 'org.jetbrains.kotlin.android' version '1.8.0' apply false
id 'com.google.dagger.hilt.android' version '2.44.2' apply false
}
tasks.register('clean') {
delete rootProject.buildDir
}
and gradle wrapper
#Tue Oct 25 07:38:32 BST 2022
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-rc-1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
all these actions have resulted in the resolution of my issue

How to fix jvm options exports javafx 11 to com.jfoenix on gradle idea?

It's been 3 days that I look on the internet how to fix this on gradle
Caused by: java.lang.IllegalAccessError: class com.jfoenix.skins.JFXTabPaneSkin (in module com.jfoenix) cannot access class com.sun.javafx.scene.control.behavior.TabPaneBehavior (in module javafx.controls) because module javafx.controls does not export com.sun.javafx.scene.control.behavior to module com.jfoenix
On simple idea projects I was adding
--add-exports javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix --add-exports javafx.controls/com.sun.javafx.scene.control=com.jfoenix --add-exports javafx.base/com.sun.javafx.binding=com.jfoenix --add-exports javafx.graphics/com.sun.javafx.stage=com.jfoenix --add-exports javafx.base/com.sun.javafx.event=com.jfoenix
I know, I have to add jvm options but how do I ?
I'm using gradle javafx 11.0.2, java 11, on intellij idea,
this is the build.gradle
plugins {
id 'java'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.8'
}
compileJava.options.encoding = 'UTF-8'
repositories {
mavenCentral()
}
dependencies {
// https://mvnrepository.com/artifact/com.jfoenix/jfoenix
compile group: 'com.jfoenix', name: 'jfoenix', version: '9.0.9'
compile group: 'de.jensd', name: 'fontawesomefx-fontawesome', version: '4.7.0-9.1.2'
// https://mvnrepository.com/artifact/de.jensd/fontawesomefx-commons
runtime group: 'de.jensd', name: 'fontawesomefx-commons', version: '9.1.2'
// https://mvnrepository.com/artifact/com.h2database/h2
compile group: 'com.h2database', name: 'h2', version: '1.4.199'
}
javafx {
version = "11.0.2"
modules = [ 'javafx.controls', 'javafx.fxml','javafx.graphics','javafx.base' ]
}
mainClassName = 'org.yanisboukir.agence.Main'
Thanks
If you are running a non modular project (you don't have module-info.java), to include the VM arguments in your run task, all you need to add to your build.gradle file is:
run {
jvmArgs = [
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED",
"--add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED",
"--add-exports=javafx.base/com.sun.javafx.binding=ALL-UNNAMED",
"--add-exports=javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED",
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED"
]
}
Note that in this case, you can't use --add-exports=...=com.jfoenix.
If you run a modular project, with a module descriptor like:
module hellofx {
requires javafx.controls;
requires javafx.fxml;
requires com.jfoenix;

opens org.openjfx to javafx.fxml;
exports org.openjfx;
}
now these are the VM arguments that you will have to include in your build file:
run {

 jvmArgs = [
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix",
"--add-exports=javafx.controls/com.sun.javafx.scene.control=com.jfoenix",
"--add-exports=javafx.base/com.sun.javafx.binding=com.jfoenix",
"--add-exports=javafx.graphics/com.sun.javafx.stage=com.jfoenix",
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix"
]

}
For newer versions of Gradle (6.x) the following worked for me:
compileJava {
options.compilerArgs.add('--add-exports=java.base/jdk.internal.vm.annotation=ALL-UNNAMED')
}
For Java test code:
compileTestJava {
options.compilerArgs.add('--add-exports=java.base/jdk.internal.vm.annotation=ALL-UNNAMED')
}
Compile-time following:
compileJava {
options.compilerArgs.add('--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix')
options.compilerArgs.add('--add-exports=javafx.controls/com.sun.javafx.scene.control=com.jfoenix')
options.compilerArgs.add('--add-exports=--add-exports=javafx.base/com.sun.javafx.binding=com.jfoenix')
options.compilerArgs.add('--add-exports=javafx.graphics/com.sun.javafx.stage=com.jfoenix')
}
Run-time following
run {

 jvmArgs = [
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix",
"--add-exports=javafx.controls/com.sun.javafx.scene.control=com.jfoenix",
"--add-exports=javafx.base/com.sun.javafx.binding=com.jfoenix",
"--add-exports=javafx.graphics/com.sun.javafx.stage=com.jfoenix"
]

}
We must set both of them. If we only set the first one idea can compile, however at the run time throw exception. Thanks #sakra #José Pereda
this didn't work for me in JDK 16:
run {
jvmArgs = [
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix",
"--add-exports=javafx.controls/com.sun.javafx.scene.control=com.jfoenix",
"--add-exports=javafx.base/com.sun.javafx.binding=com.jfoenix",
"--add-exports=javafx.graphics/com.sun.javafx.stage=com.jfoenix",
"--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix",
]
}
what worked instead is
run {
jvmArgs = [
"--add-opens=java.base/java.lang.reflect=com.jfoenix",
"--add-opens=java.base/java.lang.reflect=com.jfoenix",
"--add-opens=javafx.controls/com.sun.javafx.scene.control.behavior=com.jfoenix",
"--add-opens=javafx.base/com.sun.javafx.binding=com.jfoenix",
"--add-opens=javafx.graphics/com.sun.javafx.stage=com.jfoenix",
"--add-opens=javafx.base/com.sun.javafx.event=com.jfoenix",
]
}

Azure Pipeline Gradle build fails for Spring

Im trying to build and deploy a Spring API on Azure via a Yaml pipeline. But i get an error during the spring application gradle build saying.
Error: /home/vsts/work/1/s/gradlew failed with return code: 1
Could not find org.springframework.boot:spring-data-rest-hal-browser:
Expanding the Error,
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :compileJava FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Could not resolve all files for configuration ':compileClasspath'.
> Could not find org.springframework.boot:spring-data-rest-hal-browser:.
Required by:
project :
* 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 39s
1 actionable task: 1 executed
Error: /home/vsts/work/1/s/gradlew failed with return code: 1
at ChildProcess.<anonymous> (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4/2.151.0/node_modules/vsts-task-lib/toolrunner.js:639:25)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:886:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
##[error]Error: /home/vsts/work/1/s/gradlew failed with return code: 1
##[section]Finishing: Gradle
Things i have tried.
I have tried changing specifying the versions of spring-data-rest-hal-browser in my project from.
compile("org.springframework.boot:spring-data-rest-hal-browser")
to
compile("org.springframework.boot:spring-data-rest-hal-browser:2.4.0.RELEASE")
and finally
compile("org.springframework.boot:spring-data-rest-hal-browser:3.0.8.RELEASE")
But still the same Error results
This is my current build.gradle file in my repo
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.test.spring.api'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.11'
repositories {
mavenCentral()
}
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-data-rest")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-data-rest-hal-browser")
compile("org.springframework.data:spring-data-rest-webmvc:3.1.5.RELEASE")
}
And this is my current azure-pipelines.yml file
# Maven
# Build your Java project and run tests with Apache Maven.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/java
trigger:
- master
pool:
vmImage: 'Ubuntu-16.04'
steps:
- task: Gradle#2
inputs:
workingDirectory: '$(system.defaultWorkingDirectory)'
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
javaHomeOption: 'JDKVersion'
jdkVersionOption: '1.8'
jdkArchitectureOption: 'x64'
publishJUnitResults: false
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
- task: CopyFiles#2
displayName: 'Copy Files to: Wireframe Directory on development server'
inputs:
SourceFolder: '$(Build.SourcesDirectory)'
TargetFolder: '$(Build.ArtifactStagingDirectory)'
- script:
cd '$(Build.ArtifactStagingDirectory)';
ls
- task: FtpUpload#1
displayName: 'FTP Upload: $(Build.ArtifactStagingDirectory)'
inputs:
credentialsOption: inputs
serverUrl: '[test server url]'
username: '[test username] '
password: '[test password] '
rootDirectory: '$(Build.ArtifactStagingDirectory)'
remoteDirectory: D:\home\site\wwwroot\webapps\ROOT\
preservePaths: true
I want to be able to automatically deploy my spring application to the server URL by pushing my code to it via the Azure devops pipeline which would build and deploy the spring application.
Thanks
So i resolved the issue by making some changes to the build.gradle file and build pipeline using help from the Microsoft Azure Repository for Intellij on Github: see here
My new build.gradle file looks like this:
plugins {
id 'org.jetbrains.intellij' version '0.4.1' apply false
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
/**
*This is task for update Gradle wrapper version.
*/
task wrapper(type: Wrapper) {
gradleVersion = '4.7'
distributionUrl = "https://services.gradle.org/distributions/gradle-${gradleVersion}-all.zip"
}
apply plugin: 'io.spring.dependency-management'
group = 'com.test.spring.api'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
allprojects {
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
repositories {
mavenCentral()
}
}
task unitTest(type: Test) {
exclude '**/ApplicationTests/**'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-data-rest")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile group: 'org.springframework.data', name: 'spring-data-rest-hal-browser', version: '3.0.8.RELEASE'
compile("org.springframework.data:spring-data-rest-webmvc:3.1.5.RELEASE")
}
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
tasks.withType(FindBugs) {
ignoreFailures = true
reports {
html { enabled = true }
xml.enabled = !html.enabled
}
}
/**
* Preparing for release build
*/
task prepRelease() {
}
Also modified the azure-pipelines.yml file to include stacktrace and info to assist in debugging other gradle and build errors.
tasks: 'build --stacktrace --info'

gradle java9 Could not target platform: 'Java SE 9' using tool chain: 'JDK 8 (1.8)'

I want to use java9 on my gradle project inside eclipse oxygen. When I
run:
Run as> Gradle Test on GreeterTest.java
with the following code:
package hello.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import hello.Greeter;
class GreeterTest {
#Test
void test() {
Greeter greeter = new Greeter();
assertEquals("Hello world", greeter.sayHello());
}
}
and with the class I test as:
package hello;
public class Greeter {
public String sayHello() {
return "Hello world!";
}
}
I get the error message
Could not target platform: 'Java SE 9' using
tool chain: 'JDK 8 (1.8)'.
My eclipse.init is
-startup ../Eclipse/plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library /Users/stein/.p2/pool/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_\1.1.550.v20170928-1359
-product org.eclipse.epp.package.jee.product
-showsplash org.eclipse.epp.package.common
--launcher.defaultAction openFile
--launcher.a/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/jre/bin
-vmargs
-Dosgi.requiredJavaVersion=1.9
-Dosgi.instance.area.default=#user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dosgi.requiredJavaVersion=1.9
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM
-Xdock:icon=../Resources/Eclipse.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/
I have added JAVA_HOME
I have added the build path
I have change the compile parameter
I have set the compile parameter in the Build.Gradle.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
}
}
repositories {
mavenCentral()
}
ext.junit4Version = '4.12'
ext.junitVintageVersion = '4.12.2'
ext.junitPlatformVersion = '1.0.2'
ext.junitJupiterVersion = '5.0.2'
ext.log4jVersion = '2.9.0'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.junit.platform.gradle.plugin'
jar {
baseName = 'junit5-gradle-consumer'
version = '1.0.0-SNAPSHOT'
}
compileJava {
sourceCompatibility = 9
targetCompatibility = 9
}
compileTestJava {
sourceCompatibility = 9
targetCompatibility = 9
options.compilerArgs += '-parameters'
}
junitPlatform {
// platformVersion '1.0.2'
filters {
engines {
// include 'junit-jupiter', 'junit-vintage'
// exclude 'custom-engine'
}
tags {
// include 'fast'
exclude 'slow'
}
// includeClassNamePattern '.*Test'
}
// configurationParameter 'junit.jupiter.conditions.deactivate', '*'
// enableStandardTestTask true
// reportsDir file('build/test-results/junit-platform') // this is the default
logManager 'org.apache.logging.log4j.jul.LogManager'
}
dependencies {
// JUnit Jupiter API and TestEngine implementation
testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
// If you also want to support JUnit 3 and JUnit 4 tests
testCompile("junit:junit:${junit4Version}")
testRuntime("org.junit.vintage:junit-vintage-engine:${junitVintageVersion}")
// To avoid compiler warnings about #API annotations in JUnit code
//testCompileOnly('org.apiguardian:apiguardian-api:1.0.0')
// To use Log4J's LogManager
testRuntime("org.apache.logging.log4j:log4j-core:${log4jVersion}")
testRuntime("org.apache.logging.log4j:log4j-jul:${log4jVersion}")
// Only needed to run tests in an (IntelliJ) IDE(A) that bundles an older version
testRuntime("org.junit.platform:junit-platform- launcher:${junitPlatformVersion}")
}
task wrapper(type: Wrapper) {
description = 'Generates gradlew[.bat] scripts'
gradleVersion = '4.1'
}
What must I do to get this to run?
You should probably try to update your JAVA_HOME in system variables and
Java version used in eclipse to be consistent to
JAVA_HOME=/path/to/jdk9
In MacOSX, something like :
JAVA_HOME = /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/bin
As informed in comments, the default path on Linux would be :
/usr/lib/jvm/java-9-openjdk
From what I can see, it is the Gradle version issue. (Gradle and Java 9 compatibility issue).
You need to upgrade the wrapper to 4.3.1, cli ref:
# upgrade Gradle to 4.3.1
gradle wrapper --gradle-version 4.3.1 # not ./gradlew
Let me know if that works.
I changed the java_home and upgraded Gradle. Now it is working.
I faced the issue because in IntelliJ Idea in the Settings > Build Tools > Gradle
In "Gradle" section, Gradlje JVM used an incorrect Java version. So I specify to use JAVA_HOME and it fixes the issue.
Additionally to the other ways you tried:
Gradle has a default JVM set in your %userprofile%/.gradle/gradle.properties.
This is in the folder "C:\Users\j.gradle\gradle.properties" for me:
org.gradle.java.home=C:/Program Files/AdoptOpenJDK/jdk-11.0.7.10-hotspot
That's where you should also put your newer JVM to make sure gradle can compile newer projects.
What I did to fix this problem was I did this on my imported project build.gradle on compileJava section I changed sourceCompatibility and targetCompatibility into 8. It works for me. this happen when you import project from other resource, which is build in different version.
in Eclipse make sure you have proper settings on Gradle build configuration.
I faced the same error with different JDK version, so i used the following code which works fine.
compileJava {
options.fork = true
options.forkOptions.javaHome = file('/Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home')
targetCompatibility = 11
sourceCompatibility = 11
}
I had a similar issue with eclipse, I had to set JAVA_HOME in Properties -> Gradle.
For me the problem was that I used
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_10
targetCompatibility JavaVersion.VERSION_1_10
}
but the project was configured for Java 1.8. So I changed these to 1_8 and it works.

How do I add default JVM arguments with Gradle

I need to add default JVM options to my jar, when build with Gradle.
From the documentation I got that I have to set:
applicationDefaultJvmArgs = ["-Djavafx.embed.singleThread=true"]
I have not much experience with Gradle and the developer that wrote the build.gradle file wrote it different from what most websites give as examples.
Here is the build.gradle:
apply plugin: 'java'
apply plugin: 'eclipse'
version = '0.1'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.+'
compile 'placeholder'
}
task release(type: Jar) {
manifest {
attributes("Implementation-Title": "placeholder",
"Implementation-Version": version,
'Main-Class': 'placeholder.Application')
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
task wrapper(type: Wrapper) {
gradleVersion = '2.2.1'
}
I don't know where to put the arguments. I tried putting them in different locations, but I always get:
A problem occurred evaluating root project 'placeholder'.
> No such property: applicationDefaultJvmArgs for class: org.gradle.api.tasks.bundling.Jar_Decorated
Much Thanks,
Jhonny
From the top of my head I can think of 2 options:
Option1: Do what #Ethan said, it'll likely work:
package placeholder;
//your imports
public class Application{
static {
System.getProperties().set("javafx.embed.singleThread", "true");
}
// your code
public static void main(String... args){
//your code
}
}
Option 2: Use the application plugin + default jvm values
build.gradle:
apply plugin: 'application'
//your code
applicationDefaultJvmArgs = ["-Djavafx.embed.singleThread=true"]
Now you can run your code 2 ways:
From gradle
$gradle run
From distribution(script). from the generated script that the application plugin will provide:
$gradle clean build distZip
Then gradle will generate a zip file somewhere under ${your.projectdir}/build. Find the zip then unzip it and under /bin you'll find a ${yourproject}.bat and ${yourproject} executables. One is for Linux/mac/unix (${yourproject}) the other one is for windows (${yourproject.bat})
Option 3 (Android Developer): Use gradle.properties to set jvm argument
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx1024m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx1024m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# You can setup or customize it according to your needs and combined with the above default value.
org.gradle.jvmargs=-Djavafx.embed.singleThread=true
For more info on how to use gradle build environment on docs.gradle.org
applicationDefaultJvmArgs is provided by the Application plugin. So if you apply that plugin, the error would probably go away, and you should be able to execute the program by issuing gradle run once you set the mainClassName property to the fully qualified class name, the main method of which you want to invoke.
Using a local gradlew is the easiest.
Just append to DEFAULT_JVM_OPTS.
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m" "-XX:+AllowRedefinitionToAddDeleteMethods"'
you can use command-line with gradle task:
class AppRun extends JavaExec {
private boolean withDebug
#Option(option = "with-debug", description = "enable debug for the process. ")
public void setDebugMode(boolean debug) {
this.withDebug = debug
}
public boolean getDebugMode() {
return this.withDebug
}
}
task run(type: AppRun) {
}
then run task with options
gradle run --with-debug
set this to Your java main Class.
static {
System.setProperty("nashorn.args", "--no-deprecation-warning");
}

Categories