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) {}
}
Related
I am using JHipster 4.5.4 with Gradle as build system and would like to add Gradle Tasks for executing Liquibase tasks such as validate or reset. I used the liquibaseDiffChangelog task that ships with JHipster as a template. This task is defined like this:
task liquibaseDiffChangelog(dependsOn: compileJava, type: JavaExec) {
group = "liquibase"
if (OperatingSystem.current().isWindows()) {
dependsOn pathingLiquibaseJar
doFirst {
classpath = files(pathingLiquibaseJar.archivePath)
}
} else {
classpath sourceSets.main.runtimeClasspath
classpath configurations.liquibase
}
main = "liquibase.integration.commandline.Main"
args "--changeLogFile=src/main/resources/config/liquibase/changelog/" + buildTimestamp() +"_changelog.xml"
args "--referenceUrl=hibernate:spring:at.project.domain?dialect=org.hibernate.dialect.MySQL5InnoDBDialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
args "--username=testapp_db_user"
args "--password=secret"
args "--url=jdbc:mysql://localhost:3306/testapp_db"
args "--driver=com.mysql.jdbc.Driver"
args "diffChangeLog"
}
I started with simply exchangin the diffChangeLog with validate but then receive classpath errors. I also added a classpath argument and ended up with a task definition like this:
task liquibaseValidate(dependsOn: compileJava, type: JavaExec) {
group = "liquibase"
if (OperatingSystem.current().isWindows()) {
dependsOn pathingLiquibaseJar
doFirst {
classpath = files(pathingLiquibaseJar.archivePath)
}
} else {
classpath sourceSets.main.runtimeClasspath
classpath configurations.liquibase
}
main = "liquibase.integration.commandline.Main"
args "--changeLogFile=./build/resources/main/config/liquibase/master.xml"
args "--referenceUrl=hibernate:spring:at.project.domain?dialect=org.hibernate.dialect.MySQL5InnoDBDialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
args "--username=testapp_db_user"
args "--password=secret"
args "--url=jdbc:mysql://localhost:3306/testapp_db"
args "--driver=com.mysql.jdbc.Driver"
args "--classpath=./build/resources/main/config/liquibase/changelog/"
args "validate"
}
The master file gets read, as it mentions the correct file name, so this part is fine. But it does not recognize the path for the actual changeset files, which are referenced in the master.xml file.
This is the error message:
19:51:04.292 [main] ERROR liquibase - classpath:config/liquibase/changelog/00000000000000_initial_schema.xml does not exist
liquibase.exception.ChangeLogParseException: liquibase.exception.SetupException: classpath:config/liquibase/changelog/00000000000000_initial_schema.xml does not exist
at liquibase.parser.core.xml.AbstractChangeLogParser.parse(AbstractChangeLogParser.java:27)
at liquibase.Liquibase.getDatabaseChangeLog(Liquibase.java:229)
at liquibase.Liquibase.validate(Liquibase.java:1443)
at liquibase.integration.commandline.Main.doMigration(Main.java:1102)
at liquibase.integration.commandline.Main.run(Main.java:188)
at liquibase.integration.commandline.Main.main(Main.java:103)
Caused by: liquibase.exception.SetupException: classpath:config/liquibase/changelog/00000000000000_initial_schema.xml does not exist
at liquibase.changelog.DatabaseChangeLog.handleChildNode(DatabaseChangeLog.java:322)
at liquibase.changelog.DatabaseChangeLog.load(DatabaseChangeLog.java:282)
at liquibase.parser.core.xml.AbstractChangeLogParser.parse(AbstractChangeLogParser.java:25)
... 5 common frames omitted
Caused by: liquibase.exception.ChangeLogParseException: classpath:config/liquibase/changelog/00000000000000_initial_schema.xml does not exist
at liquibase.parser.core.xml.XMLChangeLogSAXParser.parseToNode(XMLChangeLogSAXParser.java:100)
at liquibase.parser.core.xml.AbstractChangeLogParser.parse(AbstractChangeLogParser.java:17)
at liquibase.changelog.DatabaseChangeLog.include(DatabaseChangeLog.java:478)
at liquibase.changelog.DatabaseChangeLog.handleChildNode(DatabaseChangeLog.java:320)
... 7 common frames omitted
How can I add the classpath correctly?
Related to this JHipster issue, you need to remove classpath: from your changelog paths in master.xml (located at src/main/resources/config/liquibase/master.xml). This will let you use other liquibase tasks than liquibaseDiffChangeLog. This should be fixed in the next release (v4.6.2+).
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")
I am trying to get a JavaCC plugin working properly with Gradle. The plugin generates .java files correctly, but then during the compileJavaC task it crashes and burns with cannot find symbol errors. My JavaCC .jj file contains code that references other java files that are not generated, and I am guessing that the compileJava task tries to compile the generated code without providing a reference to the non-generated code.
Here is a minimum breaking example. build.gradle:
apply plugin: 'java'
//compile .jj file in src/main/javacc
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath group: 'ca.coglinc', name: 'javacc-gradle-plugin', version: '1.0.0'
}
}
apply plugin: 'javacc'
src/main/MyClass.java:
public class MyClass {
public MyClass(){
}
}
and src/main/javacc/MyParser.jj:
options
{}
PARSER_BEGIN(MyParser)
import java.util.*;
public class MyParser {
public static void main(String[] args) throws ParseException {
MyClass mc = new MyClass();
}
}
PARSER_END(MyParser)
SKIP:
{
" "
}
TOKEN:
{
<ANYTHING: ~[]>
}
void production():
{}
{
(<ANYTHING>)+
}
Running gradle build gives the following:
gradle build
:compileJavacc
Java Compiler Compiler Version 5.0 (Parser Generator)
(type "javacc" with no arguments for help)
Reading from file C:\Users\Nate Glenn\Desktop\java_workspace\test-gradle-javacc\
src\main\javacc\MyParser.jj . . .
File "TokenMgrError.java" does not exist. Will create one.
File "ParseException.java" does not exist. Will create one.
File "Token.java" does not exist. Will create one.
File "SimpleCharStream.java" does not exist. Will create one.
Parser generated successfully.
:compileJavaC:\Users\Nate Glenn\Desktop\java_workspace\test-gradle-javacc\build\
generated\javacc\MyParser.java:5: error: cannot find symbol
MyClass mc = new MyClass();
^
symbol: class MyClass
location: class MyParser
C:\Users\Nate Glenn\Desktop\java_workspace\test-gradle-javacc\build\generated\ja
vacc\MyParser.java:5: error: cannot find symbol
MyClass mc = new MyClass();
^
symbol: class MyClass
location: class MyParser
2 errors
FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.
* 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: 9.002 secs
How can I fix my Gradle build file so that javaCompileC correctly includes non-generated files when compiling the generated files?
Your source tree for MyClass is incorrect. It should be src/main/java/MyClass.java. In gradle, just like maven, convention is that java files by default are in src/main/java, and since you're not overriding this in your build.gradle file, I assume this is just an error on your part. The plugin correctly adds the JavaCC output path to the compileJava task's classpath, so if you create your java classes in the correct path for the compileJava task, everything should be fine :)
Just tried your example this way and it works.
By the way, thanks for your contribution to the plugin.
Just some additional FYI, if you would like to overwrite the compile path, here is how you would do it:
//customized source sets to over-write the default src/main/java path
sourceSets {
main{
java {
srcDir 'Java Source'
}
resources {
srcDir 'resources'
}
}
test {
java {
srcDir 'tests'
}
}
}
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"
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
}