Gradle task --help printed to console instead of my application execution - java

This is my build.gradle file:
plugins {
id 'org.springframework.boot' version '2.1.11.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example.ProjectJar'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
jar {
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes("Main-Class": "com.example.ProjectJar.ProjectJar.FileSend" )
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
compile 'io.minio:minio:6.0.11'
}
But instead of execution of my main class that does have a main function, I get the following output:
Task :help
Welcome to Gradle 5.6.4.
To run a build, run gradle ...
To see a list of available tasks, run gradle tasks
To see a list of command-line options, run gradle --help
To see more detail about a task, run gradle help --task
For troubleshooting, visit https://help.gradle.org
BUILD SUCCESSFUL in 43ms
What should I do to have my main class execute instead of this?

Try these :
gradle clean build
This command creates the spring-boot jar file to the build/libs directory or the target directory.
we can start our application by running the following command at the command prompt:
java -jar spring-boot-web-application.jar
Another way
./gradlew bootJar
This command creates the spring-boot jar file
To run the application is by executing the following Gradle command:
./gradlew bootRun

Related

Gradle & Groovy - Error: Could not find or load main class

I can run my project using gradle run, but I can't run the jar file using java -jar. I've recreated the error with this sample project: link to project on GitHub
This is the output from running the project via gradlew
$ ./gradlew run
> Task :run
Hello world.
BUILD SUCCESSFUL in 4s
This is the output from running the project java -jar
$ ./gradlew build
BUILD SUCCESSFUL in 6s
$ java -jar build/libs/emailer.jar
Error: Could not find or load main class us.company.emailer.App
But when I unzip the jar, I can see App.class
user#computer:../libs$ unzip emailer.jar
Archive: emailer.jar
creating: META-INF/
inflating: META-INF/MANIFEST.MF
creating: us/
creating: us/company/
creating: us/company/emailer/
inflating: us/company/emailer/App.class
Here's the build.gradle
plugins {
id 'groovy'
id 'application'
}
repositories {
jcenter()
mavenCentral()
}
dependencies {
implementation 'org.codehaus.groovy:groovy-all:2.5.6'
testImplementation 'org.spockframework:spock-core:1.2-groovy-2.5'
compile 'org.apache.commons:commons-email:1.5'
}
mainClassName = 'us.company.emailer.App'
jar {
manifest {
attributes(
'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
'Main-Class': 'us.company.emailer.App'
)
}
}
sourceSets.main.java.srcDirs = ['src/main/groovy']
Here's the App.groovy
package us.company.emailer
class App {
String getGreeting() {
return 'Hello world.'
}
static void main(String[] args) {
println new App().greeting
}
}
EDIT: Adding MANIFEST.MF in response to the comment from #tkruse
Manifest-Version: 1.0
Class-Path: commons-email-1.5.jar javax.mail-1.5.6.jar activation-1.1.
jar
Main-Class: us.company.emailer.App
The problem is the classpath. If you look inside the META-INF/MANIFEST.mf file, you can see it's set to:
Class-Path: commons-email-1.5.jar javax.mail-1.5.6.jar activation-1.1.
jar
When java runs, it has no idea where any of these things are, it also requires the groovy runtime in order to understand your groovy code.
The simplest way of doing this is to bundle all your dependencies into a "fat-jar", and the simplest way of doing this with Gradle is the excellent Shadow-jar plugin.
If you add the following to your plugins block in build.gradle:
id 'com.github.johnrengelman.shadow' version '5.0.0'
(You can delete the jar block and the line that manipulates the sourceSets)
Then run ./gradlew shadowJar
You'll get a jar file emailer-all.jar
Which can be run:
$ java -jar build/libs/emailer-all.jar
Hello world.
For completeness, here's the complete build.gradle file:
plugins {
id 'groovy'
id 'application'
id 'com.github.johnrengelman.shadow' version '5.0.0'
}
repositories {
jcenter()
mavenCentral()
}
dependencies {
implementation 'org.codehaus.groovy:groovy-all:2.5.6'
testImplementation 'org.spockframework:spock-core:1.2-groovy-2.5'
implementation 'org.apache.commons:commons-email:1.5'
}
mainClassName = 'us.company.emailer.App'

Spring Boot Gradle quickbuild that skips the non-essentials

Java 8 and Gradle 4.6 here. I have a Spring Boot app with the following build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE")
}
}
plugins {
id 'java-library'
id 'checkstyle'
id 'jacoco'
}
apply plugin: 'org.springframework.boot'
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
configurations {
dev
}
dependencies {
compile(
,'ch.qos.logback:logback-classic:1.2.3'
,'org.slf4j:jul-to-slf4j:1.7.25'
,'org.apache.logging.log4j:log4j-to-slf4j:2.9.1'
,'org.apache.commons:commons-lang3:3.7'
,'org.springframework.boot:spring-boot-starter-actuator'
,'org.apache.commons:commons-text:1.2'
,'commons-beanutils:commons-beanutils-core:1.8.3'
)
testCompile(
'junit:junit:4.12'
,'org.mockito:mockito-core:2.23.0'
)
dev('org.springframework.boot:spring-boot-devtools')
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
String buildName = 'myapp'
jar {
baseName = buildName
}
bootRun {
if(project.hasProperty('debugMode')) {
jvmArgs = [ "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005" ]
}
classpath = sourceSets.main.runtimeClasspath + configurations.dev
}
checkstyle {
toolVersion = '8.12'
ignoreFailures = false
}
jacocoTestReport {
reports {
xml.enabled false
html.enabled true
html.destination file("${buildDir}/reports/jacoco/")
}
}
check.dependsOn jacocoTestCoverageVerification
jacocoTestCoverageVerification.dependsOn jacocoTestReport
So this is a Spring Boot Java app that also uses the Checkstyle and Jacoco Gradle plugins.
I consider a "full build" to be an invocation that:
Compiles
Runs Checkstyle
Runs unit tests (JUnit)
Runs Jacoco for code coverage analysis
Uses Spring Boot's libraries to build a "fat" (self-contained) executable jar
Given my current Gradle build file, I run a full build like so:
./gradlew clean build
However this can take several minutes to run through all the unit tests and has become cumbersome. I would like to introduce a
"quick build" option that only compiles the code and creates the Spring Boot fat jar for me. This will help speed up development
time tremendously.
I'm hoping to invoke the quick build like so:
./gradlew clean quickbuild
So far I've got this:
tasks.register("quickbuild") {
doLast {
// ???
}
}
But not sure how to link the compilation and fatjar tasks to it (and more importantly; skipping all the other stuff that I don't want!). Any ideas as to what I'm missing?
Update
The bootJar task doesn't seem to exist or be configured (please check my build.gradle file provided above!):
$ ./gradlew clean bootJar
FAILURE: Build failed with an exception.
* What went wrong:
Task 'bootJar' not found in root project 'myapp'. Some candidates are: 'bootRun'.
* Try:
Run gradlew tasks to get a list of available tasks. 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 0s
When I try to run bootRun:
$ ./gradlew clean bootRun
It tries to actually run my app! That's not what I want! I just want to compile and build the fat jar!
See documentation from the Java plugin here : https://docs.gradle.org/current/userguide/java_plugin.html#lifecycle_tasks
You could create a new task (quickbuild) and make it depend on the desired task (in your case it could be the assemble lifecycle task, I guess, or maybe bootJar task (for SpringBoot v2.x) or bootRepackage (for SpringBoot v1.5.x) )
tasks.register('quickbuild'){
dependsOn assemble
}
But if the only purpose of quickbuild task is to trigger the creation of the Jar, the simpliest solution is to execute assemble directly
./gradlew clean assemble

Gradle - Create jar only if tests pass

I am new to Gradle. I would like to manipulate the following build.gradle contents to do this. Instead of separately running the tests then building the jar via separate commands, I'd like to do both in one command, except that the jar does not get created if one of the tests fail (it will not even try to build the jar).
apply plugin: 'java'
apply plugin: 'eclipse'
version = '1.0'
sourceCompatibility = 1.6
targetCompatibility = 1.6
// Create a single Jar with all dependencies
jar {
manifest {
attributes 'Implementation-Title': 'Gradle Jar File Example',
'Implementation-Version': version,
'Main-Class': 'com.axa.openam'
}
baseName = project.name
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
// Get dependencies from Maven central repository
repositories {
mavenCentral()
}
test {
testLogging {
showStandardStreams = true
}
}
// Project dependencies
dependencies {
compile 'com.google.code.gson:gson:2.5'
testCompile 'junit:junit:4.12'
}
Thanks!
The simplest solution is to place all the tasks you want gradle to execute in order. So you may use the following:
gradle clean test jar
Tasks Breakout
clean: this is used mainly just to safely remove the last outdated jar (this is not mandatory);
test: execute the tests;
jar: create the jar artifact.
Key point: if one of the task fails for some reason gradle stops its execution.
So if just a single test fails for some reason an exception is thrown and the jar file is not created at all.
Alternative solution: add 'test' as dependency of 'jar'
Just to explore some other possibilities: modify the build.gralde file as follows:
[...]
jar {
dependsOn 'test'
[...]
}
[...]
Now every time you run gradle jar the test task is automatically executed before.
Emulate the pure command line solution using 'dependsOn'
To emulate the first command line approach (i.e., gradle clean test jar) using the dependency method you have to further modify the build.gradle. This is because is not assured that multiple dependsOn statements are evaluated in order:
[...]
jar {
dependsOn 'clean'
dependsOn 'test'
tasks.findByName('test').mustRunAfter 'clean'
[...]
}
[...]
Now you can use:
gradle jar
and both the tasks clean and test are executed (in the right order) before the actual jar task.

can not create RPM using gradle

I am new to java/gradle setup and was able to build a jar file using example provided here. Also implemented Jacoco code coverage tool on same.
But running into following issue
Unable to build an RPM, Tried ospackage-plugin but its just doesnt generates anything ( used example provided on plugin's github page )
Jacoco not generating highlighted source code html files ? Its generating till method breakdown like this but not able to generate individual source code files
My build.gradle file is as below
plugins {
id "nebula.ospackage" version "3.2.0"
}
apply plugin: 'nebula.ospackage'
apply plugin: 'java'
apply plugin: "jacoco"
repositories {
mavenCentral()
jcenter()
}
dependencies {
testCompile 'org.testng:testng:6.8'
compile 'log4j:log4j:1.2.17'
}
sourceSets {
main {
java { srcDir 'src/main/java/' }
resources { srcDir 'src/main/resources' }
}
test {
java { srcDir 'src/test/java/' }
resources { srcDir 'src/test/resources' }
}
}
test {
// explicitly include or exclude tests
include 'src/test/java/**'
useTestNG{
useDefaultListeners = true
}
jacoco {
append = false
destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
classDumpFile = file("$buildDir/jacoco/classpathdumps")
}
finalizedBy jacocoTestReport
}
jacocoTestReport {
reports {
xml.enabled false
csv.enabled false
html.enabled true
html.destination "${buildDir}/jacocoHtml"
}
}
jar {
baseName = 'smith'
version = '1.0'
manifest {
attributes 'Main-Class': 'src.main.java.HelloWorld '}
}
ospackage {
packageName = 'foo'
version = '1.2.3'
release = '1'
arch = I386
os = LINUX
}
// buildRpm and buildDeb are implicitly created, but can still be configured if needed
buildRpm {
arch = I386
}
The STDOUT is as following
project]$ /opt/gradle/bin/gradle build
:compileJava
:processResources UP-TO-DATE
:classes
:jar
:assemble
:compileTestJava
:processTestResources
:testClasses
:test
:jacocoTestReport
:check
:build
BUILD SUCCESSFUL
Total time: 11.258 secs
This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.9/userguide/gradle_daemon.html
Any pointers on whatever i am overlooking above will be highly appreciated.
Also feel free to let me know in case any standard/convention is not followed
Thanks
You need to run the buildRpm task.
gradle buildRpm
If you want this task to run when running gradle build just configure a dependency in your build.gradle file
build.dependsOn buildRpm
In addition you can add below variables in your rpm task to make your RPM more standard
requires('package name') //required package to run your RPM to be pre installed, will fail if it is not.
preInstall('path_to_file') //script to be executed before installing RPM
preUninstall('path_to_file') //script to be executed before uninstalling RPM
postInstall('path_to_file') //script to be executed after installing RPM
preUninstall('path_to_file') // script to be executed after uninstalling RPM
archiveName //the name you want to give to your RPM.
epoch //Epoch, defaults to 0
user //Default user to permission files to
permissionGroupdisplay
packageGroup
buildHost
summary
packageDescription
license
packager
distribution
vendor
url
type //type e.g. binary
//below three variables are used for signing of the RPM
signingKeyId
signingKeyPassphrase
signingKeyRingFile
sourcePackage
//if you want to include some files in your rpm
def fileToInclude = fileTree(dir:"pathToFile", include : "file" )
from (fileToInclude) {
fileMode 0500 // file level permission
into "installation Location" //locationToPlaceTheFile
}
for more details and e.g. refer this link

how to run after compiling thru gradle?

I am using the java plugin in my build.gradle.
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'xyz:xyz:4.11'
}
sourceSets {
test {
java {
srcDir 'agent'
}
}
}
I am generating the .class files by doing
$ gradle compileJava
Now that the .class files have been generated in build/, how do I run my code? One of the class files contains the main. I want to do something like this from a gradle task:
CLASSPATH=./mysql-connector-java-commercial-5.1.13-bin.jar:. $JAVA_HOME/bin/java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=10000 Collector arg1
You may want to take a look at Gradle Application Plugin.
With it, you will be able to run your application just using a run task.
Based on ghik's answer, I add these to my gradle.build script:
apply plugin:'application'
....
dependencies {
....
runtime 'mysql:mysql-connector-java-commercial:5.1.13'
}
mainClassName = "Collector"
run {
args 'arg1'
jvmArgs '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=10000'
}

Categories

Resources