Gradle to execute Java class (without modifying build.gradle) - java

There is simple Eclipse plugin to run Gradle, that just uses command line way to launch gradle.
What is gradle analog for maven compile and run
mvn compile exec:java -Dexec.mainClass=example.Example
This way any project with gradle.build could be run.
UPDATE: There was similar question What is the gradle equivalent of maven's exec plugin for running Java apps? asked before, but solution suggested altering every project build.gradle
package runclass;
public class RunClass {
public static void main(String[] args) {
System.out.println("app is running!");
}
}
Then executing gradle run -DmainClass=runclass.RunClass
:run FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':run'.
> No main class specified

There is no direct equivalent to mvn exec:java in gradle, you need to either apply the application plugin or have a JavaExec task.
application plugin
Activate the plugin:
plugins {
id 'application'
...
}
Configure it as follows:
application {
mainClassName = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "NULL"
}
On the command line, write
$ gradle -PmainClass=Boo run
JavaExec task
Define a task, let's say execute:
task execute(type:JavaExec) {
main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
classpath = sourceSets.main.runtimeClasspath
}
To run, write gradle -PmainClass=Boo execute. You get
$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!
mainClass is a property passed in dynamically at command line. classpath is set to pickup the latest classes.
If you do not pass in the mainClass property, both of the approaches fail as expected.
$ gradle execute
FAILURE: Build failed with an exception.
* Where:
Build file 'xxxx/build.gradle' line: 4
* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.

You just need to use the Gradle Application plugin:
apply plugin:'application'
mainClass = "org.gradle.sample.Main"
And then simply gradle run.
As Teresa points out, you can also configure mainClass as a system property and run with a command line argument.

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.
Both gradle build and gradle -PmainClass=foo runApp work with this:
task runApp(type:JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}
where you set your default main class.

You can parameterise it and pass gradle clean build -Pprokey=goodbye
task choiceMyMainClass(type: JavaExec) {
group = "Execution"
description = "Run Option main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('prokey')){
if (prokey == 'hello'){
main = 'com.sam.home.HelloWorld'
}
else if (prokey == 'goodbye'){
main = 'com.sam.home.GoodBye'
}
} else {
println 'Invalid value is enterrd';
// println 'Invalid value is enterrd'+ project.prokey;
}

Related

Could not determine the dependencies of task -testone

I started learning Gradle (Java + Gradle) and created this very basic - build.gralde - file.
task testone(type: Test) {
println ("Started TestSetUp")
}
In Console when ran command -> gradlew testone -- intellij is throwing error:
> Configure project :
Started TestSetUp
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':testone'.
I think i can help you with that , By changing the type from Test to Copy , this will build perfectly , Copy is a defined type in gradle and running gradle testone -q will show your output .
I think the problem is with your defined type , by declaring the type as Test you need to add more configuration for this , because the error i got when i tried to register the task like
tasks.register testone(type: Test) {
println ("Started TestSetUp")
}
was Could not find method testone() for arguments [{type=class org.gradle.api.tasks.testing.Test} so your issue is with the Test type , i spose your missing some extra configuration .
When you’re using a JVM language plugin — such as the Java Plugin —
you will automatically get the following:
A dedicated test source set for unit tests
A test task of type Test that runs those unit tests
In "build.gradle", after adding java plugin, the task ran successfully.
plugins {
id 'java'
}
task testone(type: Test) {
println ("Task of type Test Success")
}

gradle: compileJava? Found module. compileTestJava? Module foo not found?

I'm building a project with quite a few sub projects. Each one is a module.
With one of those subprojects in particular, I'm getting:
Task :foo:compileTestJava FAILED
error: module not found: foo
1 error
Note that both compileJava and classes (and an empty processResources if we must be pedantic) both completed successfully.
The build.gradle for this subproject is trivial:
ext.someVar = 'someValue'
dependencies {
compile project(':some.other.subproject.used.in.lots.of.other.places1')
compile project(':some.other.subproject.used.in.lots.of.other.places2')
}
That's it. Yes, these subprojects have been used together in some of those lots.of.other.places.
The main project has a highly non-trival build.gradle. It has an extensive subprojects {}, much of which is a test {}. This section of the build works just fine for the other 10+ subprojects. What it does not have is anything that treats individual subprojects differently. It does not have a custom compileTest, and ext.someVar is used in path construction, not conditions.
I get the same output when I run gradle (5.2.1) either from within IDEA or from the command line.
gradlew --console verbose just made the output prettier.
gradlew -d added quite a bit of noise, but no new signal:
I've run gradlew clean compileTestJava (many times). No change.
I've manually deleted the .gradle folder, then run. No change.
I ran with -s, and it gave me this:
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':foo:compileTestJava'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:121)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:117)
at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:184)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ResolveIncrementalChangesTaskExecuter.execute(ResolveIncrementalChangesTaskExecuter.java:84)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:91)
at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:74)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:109)
at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:94)
What could have gone wrong here? Where else can I look for a cause?

Run gradle task JavaExec in Android Gradle Plagin?

I try to create gradle task with type JavaExec.
In gradle documentation I found than I need to aply java plugin. But this plugin is incompatible with android plugin.
If I'm not apply java plugin I receive this error:
Error: Could not find or load main class package.TestM
Example my task:
task testA(type: JavaExec) {
main = 'package.TestM'
}
If I create java library module with same task I receive same error:
Error: Could not find or load main class
Maybe I need set classpath variable? How can I get classpath in Java module in Android Studio?
task testA(type: JavaExec) {
classpath += files(getBuildDir().toString() + "/intermediates/classes/debug")
main = 'package.TestM'
}
maybe it is a good reason replace "debug" with a buildVariant variable.

gradle 3.5 do not recognize class from terminal

I'm using Intillij with gradle 3.5 and I want to call specific class in project. in me build.gradle I have
ext.testFile = System.getProperty('Test_Plan') ?: 'testng.xml'
test {
ignoreFailures = true
testLogging {
events 'started', 'passed'
}
useTestNG {
suites "src/main/resources/${testFile}"
}
}
that use to call suite in my project, but I'll want to ignore the 'test' and just call from terminal
gradle test --tests TC1001 or gradle test -Dtest.single=TC1001
and this 2 options give the error
* What went wrong:
Execution failed for task ':test'.
No tests found for given includes: [com.automation.navigateSuite.TC1001]
the directory hierarchy is
src/test/java/com.automation/navigateSuite/TC1001.java

Can't execute debug task in NetBeans after switching to Gradle

I've installed the Gradle-support plugin in Netbeans and I can build and run the project just fine. When I try to run in debug mode, I get the following output:
Executing: gradle debug
:debug
Cannot execute debug because the property "mainClass" is not defined or empty.
BUILD SUCCESSFUL
Total time: 0.222 secs
I'm using:
Oracle Java 1.8
Gradle 1.12
Netbeans 8.0
Gradle-Support 1.3.0
LinuxMint 16
Why can't I run my debugger?
Add something like
if (!hasProperty('mainClass')) {
ext.mainClass = 'com.foo.acme.Main'
}
to your build.gradle. It will tell Gradle plugin what class to use when starting your application. Perhaps that should be customizable in the UI but I cannot see it now.
Another solution to this problem is to create a new debug task. Similar to the gradle run task you can just add the following task to your build.gradle file:
task debug(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
In addition to Radim's answer the way to customize the mainClass parameter in the Netbeans UI.
In the properties of a Netbeans gradle project go to "Built-In Tasks/Debug", unclick the "Inherit" and add "-PmainClass=aaa.bbb.ccc" to the arguments.
I guess this should also be done for the run task.
It's the same idea like run/debug single file which already take the selected file as parameter mainClass.
I had a similar problem and was able to fix it setting Options / Miscellaneous / Gradle / Task Execution / Automatic tasks to "NetBeans should not add tasks automatically".

Categories

Resources