How to pass parameters to main method using Gradle? - java

I have to pass two arguments to my main method. My build script is
// Apply the java plugin to add support for Java
apply plugin: 'java'
// In this section you declare where to find the dependencies of your project
repositories {
// Use 'maven central' for resolving your dependencies.
mavenCentral()
}
// In this section you declare the dependencies for your production and test code
dependencies {
compile 'com.example:example-core:1.7.6'
}
task main(type: JavaExec, dependsOn: classes) {
description = 'This task will start the main class of the example project'
group = 'Example'
main = 'com.example.core.Example'
classpath = sourceSets.main.runtimeClasspath
}
If I try:
gradlew main doc.json text.txt
Then an error occured.
org.gradle.execution.TaskSelectionException: Task 'doc.json' not found in root project
How can I pass arguments to my main method command line easily?

task run(type: JavaExec) {
main = "pkg.MainClass"
classpath = sourceSets.main.runtimeClasspath
args = ["arg1", "arg2"]
}

You should use use -P as listed in the Gradle command line documentation.
For example, the following will work:
gradlew main -Parg1=doc.json --project-prop arg2=text.txt
And you access them in your Gradle script like this:
println "$arg1 $arg2"

task run1(type: JavaExec) {
main = "pkg.mainclass"
classpath = sourceSets.main.runtimeClasspath
args = ["$arg1","$arg2",...]
}
//I have named as run1 it can be any task name
While invoking the gradle script:
c:\> gradle run1 -Parg1="test123" -Parg2="sss"

Related

How to generate cucumber html report with attached failed screenshot and cucumber.json file using gradle based project

Using gradle, I am trying generate cucumber html report with failed screenshot attached to it for security reason I cannot have online plugins in build.gradle file so I have to download required jar and plugins and implement and configure library manually in build.gradle file.
Please suggest how can configure TestRunner file in build.gradle and generate cucumber html report with cucumber.json file
build.gradle file
plugins {
id 'java'
id 'idea'
}
group 'org.example'
version '1.0-SNAPSHOT'
configurations {
cucumberRuntime.extendsFrom testRuntime
}
task cucumber() {
dependsOn assemble, compileTestJava
doLast {
javaexec {
main = "io.cucumber.api.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty', '--glue', 'stepDef', 'src/test/java']
}
}
}
repositories {
mavenCentral()
}
dependencies {
implementation fileTree(dir:System.getProperty("user.dir")+'/Plugin',include:['*.jar'])
implementation files('junit-4.12')
implementation files('testng-6.7.jar')
implementation files('junit-jupiter-api-5.6.2')
implementation files('hamcrest-all-1.3')
.....................
TestRunner file
package TestRunner;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "src/test/resources",
glue = "StepDefs",
plugin = {
"pretty", "html:target/cucumber-html-report", "json:target/cucumber.json", "pretty:target/cucumber-pretty.txt"
}
)
public class TestRunner {
}
Whatever StepDefs may be ...
Running with gradle cucumber --info might be useful for debugging... because the error message finished with non-zero exit value 1 just indicates "error" or "no success".
You'd probably need these Java dependencies, to begin with:
testImplementation 'io.cucumber:cucumber-java:6.5.0'
testImplementation 'io.cucumber:cucumber-junit:6.5.0'
And one might have to add gradle.cucumber as the --glue into the arguments args, as the documentation suggests. Task dependency compileTestJava should rather be testClasses.
html generally is a plugin, which expects an output directory, therefore this should look alike this:
task cucumber() {
dependsOn assemble, testClasses
doFirst {
}
doLast {
javaexec {
main = 'io.cucumber.core.cli.Main'
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = [
'--plugin', 'pretty', 'html:target/reports',
'--glue', 'gradle.cucumber',
'src/test/resources'
]
}
}
}
These args can also be annotated in Java; not sure which of them takes precedence.It probably makes no sense and only creates a mess, when defining the arguments twice.
Make sure to follow instruction #4:
Add feature .feature files and associated step mapping classes .java in src/test/resources and src/test/java respectively in a gradle.cucumber package.
-g, --glue PATH Where glue code (step definitions, hooks and plugins) are loaded from.
When running with jUnit, one can also pass options with a junit-platform.properties file.
The most easy might be to start with the cucumber-java-skeleton (it is known to be working).
It didn't work for me, If I run this cucumber task it gives me error
Task :cucumber FAILED
Error: Could not find or load main class io.cucumber.api.cli.Main
Caused by: java.lang.ClassNotFoundException: io.cucumber.api.cli.Main
Error: Could not find or load main class io.cucumber.api.cli.Main
I have created one task cucumberRunner which executes the TestRunner.java file, it is creating cucumber.json file and html report but htlm
report but HTML report is not expected is weird no graphics and colorless colorless
build.gradle I'm using:
```
configurations {
cucumberRuntime {
extendsFrom testRuntime
}
}
task cucumber() {
dependsOn assemble, testClasses
doFirst {
}
doLast {
javaexec {
main = 'io.cucumber.api.cli.Main' // tried with io.cucumber.core.cli.Main
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = [
'--plugin', 'pretty', 'html:target/reports',
'--glue', 'gradle.cucumber',
'src/test/resources'
]
}
}
}
task cucumberRunner(type: Test) {
include '**/**TestRunner.class'
}
Also I have added jars
implementation files('junit-4.12')
implementation files('testng-6.0.jar')
implementation files('cucumber-core-6.0.0')
implementation files('cucumber-java-6.0.0')
implementation files('cucumber-plugin-6.0.0')
implementation files('cucumber-junit-6.0.0')
implementation files('cucumber-testng-6.0.0')
implementation files('cucumber-jvm-deps-1.0.5')
implementation files('cucumber-gherkin-6.0.0')
implementation files('cucumber-java8-6.0.0')
implementation files('cucumber-html-0.2.3')
```

How to include plugin dependencies in JavaExec task classpath?

I am using JavaExec tasks to run different classes, but whenever I try to run one of the tasks using gradle <task>, I get an error saying Error: JavaFX runtime components are missing, and are required to run this application.
If I just set mainClassName='exercise1.Cards' or whatever other className, running gradle run works completely fine. I'm guessing that the JavaFX classes are not found when running classes with JavaExec and I'm wondering how I can include them.
build.gradle:
plugins {
id 'java'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.7'
}
version '1.0-SNAPSHOT'
sourceCompatibility = 11
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
javafx {
modules = [ 'javafx.controls' ]
}
task runExercise1(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'exercise1.Cards'
}
task runExercise2(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'exercise2.InvestmentCalculator'
}
task runExercise3(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'exercise3.PointCircle'
}
task runExercise4(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'exercise4.OccurrenceHistogram'
}
The org.openjfx.javafxplugin plugin manages for you a few things.
When you add to your build file:
javafx {
modules = [ 'javafx.controls' ]
}
the plugin translates that into something like:
run {
doFirst {
jvmArgs = ['--module-path', classpath.asPath,
'--add-modules', 'javafx.controls']
}
}
However, if you create a new JavaExec task, it seems the plugin doesn't process it.
Given the error you have posted:
Error: JavaFX runtime components are missing
it is clear that a possible fix is to do exactly what the plugin does and add the expected jvm args when using modular dependencies.
So this should work:
task runExercise1(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
jvmArgs = ['--module-path', classpath.asPath,
'--add-modules', 'javafx.controls' ]
main = 'exercise1.Cards'
}
Alternatively you could create a launcher class that doesn't extend from Application, as that will bypass the modular check (as explained here).
public class Launcher {
public static void main(String[] args) {
// optionally process args to select class to run
Cards.main(args);
}
}
Then you could add your task, and even uses runtime arguments to select the main class to run from the launcher.
task runExercise1(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'exercise1.Launcher'
args 'exercise1' // <-- optionally select class to run
}

How to pass multiple parameters in command line when running gradle task?

I've got a java and groovy classes that are being run by gradle task. I have managed to make it work but I do not like the way I have to pass the parameters in command line. Here is how I do it currently via command line: gradle runTask -Pmode"['doStuff','username','password']"
my build.gradle code which takes these parameters looks like this:
if (project.hasProperty("mode")) {
args Eval.me(mode)}
and then I use my arguments/parameters in my java code as follows:
String action = args[0]; //"doStuff"
String name = args[1]; .. //"username"
I was wondering is there a way to pass the parameters in a better way such as:
gradle runTask -Pmode=doStuff -Puser=username -Ppass=password
and how to use them in my java classes.
JavaExec may be the way to go. Just declare a task and pass project parameters to java app:
task myExecTask(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'com.project.MyApplicationMainClass'
args project.getProperty('userName') + ' ' + project.getProperty('password');
}
To run it, simply write gradle myExecTask -PuserName=john -Ppassword=secret
This is working for me:
task myExecTask(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'com.project.MyApplicationMainClass'
args(user, pass); // no need to access user and pass via project.getProperty()
}
args needs to be built as a List of Strings for java main to use.
args now should be in the form of : ['myusername', 'mypassword']
this is the task I had to create for passing arguments through gradle
task
task cucumber() {
dependsOn assemble, compileTestJava
doLast {
javaexec {
systemProperties = [
usr: project.getProperty('usr'),
pwd: project.getProperty('pwd')
]
main = "io.cucumber.core.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty', '--glue', 'location to step def', 'location to feature files']
}
}
}
in order to execute test
$ gradle cucumber -Pusr=<username> -Ppwd=<password>
to access args in your code System.getProperty("usr"), System.getProperty("pwd")

How to pass arguments to gradle from commandline

I try to pass arguments from command line to gradle.
My build.gradle is:
task execute(type:JavaExec) {
main = mainClass
classpath = sourceSets.main.output
}
When I do:
gradle -PmainClass=Hello execute
I get this:
FAILURE: Build failed with an exception.
* Where:
Build file '/home/example2/build.gradle' line: 7
* What went wrong:
A problem occurred evaluating root project 'example2'.
> Could not find property 'sourceSets' on task ':execute'.
My question is that what should I provide for main? name of any java file package? any specific path? What should actually be sourceSet?
Your minimal build.gradle file should look like this:
apply plugin: 'java'
task execute(type:JavaExec) {
main = mainClass
classpath = sourceSets.main.output
}
And you need a java class located in src/main/java/Hello.java like this:
public class Hello {
public static void main(String[] a) {}
}

How to execute a task of type 'JavaExec' before compileJava

I need to execute a java class which has a main method in it before compiling the code. This is what I have tried so far:
task runSimple(type: JavaExec) {
main = 'jjrom.ObjectGen'
classpath = sourceSets.main.runtimeClasspath
File prop1 = file(propFilePath)
args '-sqlserver', '-force', prop1.path
println "I'm done executing."
}
compileJava {
dependsOn runSimple
}
When I execute this script with the command "gradle compileJava" , I get this error message:
I'm done executing.
FAILURE: Build failed with an exception.
What went wrong: Circular dependency between the following task: :classes --- :compileJava --- :runSimple --- :classes (*)
If you need to execute this class before compiling the code, you can't give it classpath = sourceSets.main.runtimeClasspath. The latter includes the compiled code, and so Gradle automatically infers runSimple.dependsOn compileJava, which together with your compileJava.dependsOn runSimple gives a cyclic task dependency. (To be precise, Gradle infers runSimple.dependsOn classes, which in turn depends on compileJava.)
If you need to run JavaExec only with dependecies classpath, just change classpath variable to something like:
classpath = configurations.compile
Or if you are interested in very specific classpath, you could add custom configuration like this:
configurations {
customClasspath
}
dependencies {
customClasspath files('path/to/your.jar')
}
task runSimple(type: JavaExec) {
main = 'jjrom.ObjectGen'
classpath = configurations.customClasspath
File prop1 = file(propFilePath)
args '-sqlserver', '-force', prop1.path
println "I'm done executing."
}
compileJava {
dependsOn runSimple
}

Categories

Resources