How do I add default JVM arguments with Gradle - java

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");
}

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

Black Duck fails to run gradlew dependencies successfully

Since upgrading from Gradle 6.7.1 to 7.0 (which may be a red herring), Black Duck scans of my Gradle project now fail.
Here is the error message:
* Where:
Initialization script '/root/blackduck/runs/2022-01-18-19-06-00-216/shared/gradle/init-detect.gradle' line: 40
* What went wrong:
Execution failed for task ':dependencies'.
> No signature of method: org.gradle.api.tasks.diagnostics.internal.dependencies.AsciiDependencyReportRenderer.startProject() is applicable for argument types: (org.gradle.api.internal.project.DefaultProject_Decorated) values: [root project '<redacted&gt']
Possible solutions: startProject(org.gradle.api.tasks.diagnostics.internal.ProjectDetails), startProject(org.gradle.api.tasks.diagnostics.internal.ProjectDetails)
Builds are successful when the Gradle build is run without Black Duck.
The Black Duck scan is run with the following command:
bash detect.sh --blackduck.url=<redacted> --blackduck.trust.cert=true --blackduck.api.token=<redacted> --detect.project.name=<redacted> --detect.project.version.name=Developer --detect.source.path=.
Here is my full build.gradle:
buildscript {
repositories {
maven {
url "https://<redacted>/nexus/repository/maven-central"
}
maven {
url "https://<redacted>/nexus/repository/thirdparty"
}
maven {
url "https://<redacted>/nexus/repository/gradle-plugins"
}
}
}
plugins {
id "java"
}
def nexusUsername = (System.getenv("NEXUS_USERNAME") != null ? System.getenv("NEXUS_USERNAME") : (project.hasProperty('NEXUS_USERNAME') ? "$NEXUS_USERNAME" : ""))
def nexusPassword = (System.getenv("NEXUS_PASSWORD") != null ? System.getenv("NEXUS_PASSWORD") : (project.hasProperty('NEXUS_PASSWORD') ? "$NEXUS_PASSWORD" : ""))
repositories {}
ext {}
dependencies {}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
sourceCompatibility = 11
targetCompatibility = 11
sourceSets {
main {
java {
srcDirs = ['src/main/java']
}
}
}
My ideas for what could be wrong:
There is a bug in the auto-generated /root/blackduck/runs/2022-01-18-19-06-00-216/shared/gradle/init-detect.gradle file (maybe Black Duck doesn't play nice with Gradle 7.0)
I run the detect.sh script with the wrong arguments
There is something wrong with my build.gradle file
I am looking for any suggestions on how to solve this problem so that my Black Duck scans can run successfully once more.
The problem was I was using an older version of the Black Duck detect.sh script. I was using version 6.9.1. Once I upgraded to using version 7.6.0, the Black Duck scan worked once more.
To use the new version of the script, you can do the following (note the detect7.sh in the URL; if you download plain detect.sh you will get an old version):
curl --fail https://detect.synopsys.com/detect7.sh -o detect.sh
export DETECT_LATEST_RELEASE_VERSION=7.6.0
bash detect.sh <args>

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 to pass dynamic input pararm to gradle java exec task?

I have this Gradle task:
task resources_cleaner_bl(type: JavaExec) {
classpath sourceSets.main.runtimeClasspath
systemProperties['cleanTarget'] = 'bl'
main = "com.m.ResourcesCleanerRunner"
}
How can I edit this such that 'bl' will be entered dynamically when I run this gradle task.
You can simply eliminate the configuration systemProperties['cleanTarget'] = 'bl' by setting the system property from the command line using the -D flag, i.e. running gradlew resources_cleaner_bl -DcleanTarget=bl.
You can read more about project and system properties in Gradle user guide here.

How to pass JVM options from bootRun

I'm developing simple Spring web application that communicates with remote host and I would like to test it locally behind corporate proxy.
I use "Spring Boot" gradle plugin and the question is how can I specify proxy settings for JVM?
I have try several ways to do it:
gradle -Dhttp.proxyHost=X.X.X.X -Dhttp.proxyPort=8080 bootRun
export JAVA_OPTS="-Dhttp.proxyHost=X.X.X.X -Dhttp.proxyPort=8080"
export GRADLE_OPTS="-Dhttp.proxyHost=X.X.X.X -Dhttp.proxyPort=8080"
But it seems like none of them work - "NoRouteToHostException" throws in "network" code.
Also, I have added some extra code to debug JVM start arguments:
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
for (String arg: arguments) System.out.println(arg);
And only one argument was printed: "-Dfile.encoding=UTF-8".
If I set system property in code:
System.setProperty("http.proxyHost", "X.X.X.X");
System.setProperty("http.proxyPort", "8080");
Everything works just fine!
Original Answer (using Gradle 1.12 and Spring Boot 1.0.x):
The bootRun task of the Spring Boot gradle plugin extends the gradle JavaExec task. See this.
That means that you can configure the plugin to use the proxy by adding:
bootRun {
jvmArgs = "-Dhttp.proxyHost=xxxxxx", "-Dhttp.proxyPort=xxxxxx"
}
to your build file.
Of course you could use the systemProperties instead of jvmArgs
If you want to conditionally add jvmArgs from the command line you can do the following:
bootRun {
if ( project.hasProperty('jvmArgs') ) {
jvmArgs project.jvmArgs.split('\\s+')
}
}
gradle bootRun -PjvmArgs="-Dwhatever1=value1 -Dwhatever2=value2"
Updated Answer:
After trying out my solution above using Spring Boot 1.2.6.RELEASE and Gradle 2.7 I observed that it was not working as some of the comments mention.
However, a few minor tweaks can be made to recover the working state.
The new code is:
bootRun {
jvmArgs = ["-Dhttp.proxyHost=xxxxxx", "-Dhttp.proxyPort=xxxxxx"]
}
for hard-coded arguments, and
bootRun {
if ( project.hasProperty('jvmArgs') ) {
jvmArgs = (project.jvmArgs.split("\\s+") as List)
}
}
for arguments provided from the command line
bootRun {
// support passing -Dsystem.property=value to bootRun task
systemProperties = System.properties
}
This should pass all JVM options to the app started via bootRun.
In gradle build script, define systemProperties for run task.
//to provide the properties while running the application using spring-boot's run task
run {
systemProperties['property name'] = 'value'
}
and gradle run should accept this value.
Or define a project level property as mentioned in
http://forums.gradle.org/gradle/topics/how_can_i_provide_command_line_args_to_application_started_with_gradle_run
#marvin, thanks for your post it was very helpful.
Sharing how I used it:
test {
// support passing -Dsystem.property=value to bootRun task
systemProperties = System.properties
}
I have JUnit tests that I wanted to skip unless a property was used to include such tests. Using JUnit Assume for including the tests conditionally:
//first line of test
assumeThat(Boolean.parseBoolean(System.getProperty("deep.test.run","false"),true)
Doing this with gradle required that the system property provided at the time of running gradle build, shown here,
gradle build -Ddeep.test.run=true
was indeed passed through to the tests.
Hope this helps others trying out this approach for running tests conditionally.
bootRun {
args = ['myProgramArgument1', 'myProgramArgument2']
}
Using jvmArgs may cause JVM start issues. Using args allows you to pass your custom program arguments
It seems to work:
bootRun {
systemProperties "property1": "value1", "property2": "value2"
}
I got into a similar problem, bootRun needed some parameters but I wouldn't feel like modifying bootRun as I want to keep some flexibility and stick to standard bootRun behaviour. My suggestion is to add some custom tasks (let's say bootRunDev, bootRunProxy) that extends bootRun, as described in the following code snippet
task bootRunPxy(type: org.springframework.boot.gradle.run.BootRunTask, dependsOn: 'build') {
group = 'Application'
doFirst() {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
systemProperty 'http.proxyHost', 'xxxxx'
systemProperty 'http.proxyPort', 'yyyyy'
}
}
I don't have an environment to exercise the script but I used this approach to pass profile to spring using the property spring.profiles.active.
Credits should go to Karol Kaliński
It's worth mentioning, here, that some systems that use Gradle and Spring Boot are starting JVM outside of build.gradle, e.g. in a Dockerfile.
It's not pointless to mention this on a thread specifically about bootRun! I wound up here because this particular post is a magnet for searches about jvm options in the context of a Spring Boot app compiled / run under gradle. (All the advice I found for adding java.net.http.httpclient logging said "add it to bootRun's jvmArgs". Nothing happened, though.
So, if you happen to run your gradle-built Spring Boot app from a Docker container, you'll want to add your JVM params to an env var in your project's Dockerfile, like so, e.g.-
...
ENV JAVA_OPTS "${JAVA_OPTS} \
-server \
-Duser.timezone=UTC \
-XX:InitialRAMPercentage=50 \
-XX:MaxRAMPercentage=50 \
-Djavax.net.ssl.trustStorePassword=elvislives \
-Djavax.net.ssl.trustStoreProvider=BCFIPS \
-Djavax.net.ssl.trustStoreType=BCFKS \
-Djdk.internal.httpclient.debug=true \
-Djava.util.logging.manager=org.apache.logging.log4j2.jul.LogManager \
-Djdk.httpclient.HttpClient.log=errors,requests,headers,frames[:control:data:window:all..],content,ssl,trace,channel \
"
...
ENTRYPOINT java ${JAVA_OPTS} -cp app:app/lib/* com.mygreatcompany.theapp
For development as Docker Container add to run_script.sh as JAVA_OPTS
JAVA_OPTS="-XX:+UseG1GC
-Xms512m
-Xmx2048m
--add-opens java.base/java.util=ALL-UNNAMED -Dspring.profiles.active=$PROFILE,discovery"

Categories