Why won't my Groovy main class execute from the built jar? - gradle

I'm trying to build an executable JAR with a Groovy main class. I can get a Java main class to run exactly as expected, but the Groovy equivalent just isn't found and won't run.
In src/main/groovy/foo/Test.groovy:
package foo
public class Test { // (Yes, the public keywords here and below are redundant)
public static void main(String[] args) {
println "groovy world"
}
}
In src/main/groovy/foo/Test2.java:
package foo;
public class Test2 {
public static void main(String[] args) {
System.out.println("java world");
}
}
Gradle file:
plugins {
id 'java'
id 'groovy'
id 'application'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
mainClassName = 'foo.Test'
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.7'
}
jar {
manifest {
attributes 'Main-Class': mainClassName
}
}
I build a JAR:
$ ./gradlew build
And try and run it (overriding the manifest Main-Class):
$ java -cp build/libs/test-groovy-main.jar foo.Test2
java world
$ java -cp build/libs/test-groovy-main.jar foo.Test
Error: Could not find or load main class foo.Test
If I turn on verbose output whilst doing this, in the second case I see "Loaded foo.Test2", but no "Loaded foo.Test" in the first.
I had thought that Groovy source compiles to plain java classes, and indeed decompiling the Test.class file I can see a public static main(String...) method in a public Test class. What am I doing wrong?
I'm using Gradle 2.6, Java 1.8.0 and Groovy 2.4.7 on Ubuntu 16.04.
I have the test case in version control here:
https://github.com/wu-lee/test-groovy-main

Adding of from section worked for me:
jar {
manifest {
attributes 'Main-Class': mainClassName
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
it puts the org.codehaus.groovy:groovy-all:2.4.7 dependency to your jar.
UPD
Created a pull-request https://github.com/wu-lee/test-groovy-main/pull/1

Related

Task 'run' not found in root project

My "build.gradle" file:
apply plugin: 'java'
sourceSets {
main {
java {
srcDir 'src'
}
}
test {
java {
srcDir 'test'
}
}
}
My "Main.java" file in "./src/" directory:
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello Gradle");
}
}
I get this error:
Task 'run' not found in root project 'gradleNew'
Sorry for the stupid question... I didn't use Gradle before
The java plugin does not include the run task, which I suppose your gradle build requires somewhere in your app.
Change the java plugin to application and you should be fine.
To verify this, you can go to your project folder inside you terminal and run gradle tasks. You should see the run task listed among other tasks.
I hope that helps.
I just add this code and my app run:
plugins {
id 'application'
}
Try this instead:
group 'com.example'
version '1.0'
apply plugin: 'application' // implicitly includes the java plugin
sourceCompatibility = 1.11 // java version 11
repositories {
mavenCentral()
}
dependencies {
// your dependencies
}
sourceSets {
main {
java {
srcDirs = ['src/main/java']
}
resources {
srcDirs = ['src/main/resources']
}
}
}
I typically use something similar to this for my projects. You can then explicitly create the relevant dirs for src/test code, or sometimes the IDE will do it for you when you point it to the relevant build.gradle file (you can typically restart the IDE and it will pick up the file, or you can open a new project and select the build.gradle file as the project to open if it doesn't identify it right away).

execute JavaExec task using gradle kotlin dsl

I've created simple build.gradle.kts file
group = "com.lapots.breed"
version = "1.0-SNAPSHOT"
plugins { java }
java { sourceCompatibility = JavaVersion.VERSION_1_8 }
repositories { mavenCentral() }
dependencies {}
task<JavaExec>("execute") {
main = "com.lapots.breed.Application"
classpath = java.sourceSets["main"].runtimeClasspath
}
In src/main/java/com.lapots.breed I created Application class with main method
package com.lapots.breed;
public class Application {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
But when I try to execute execute tasks it fails with the error that task doesn't exist. Also when I list all the available tasks using gradlew tasks it doesn't show execute task at all.
What is the problem?
The following build script should work (Gradle 4.10.2, Kotlin DSL 1.0-rc-6):
group = "com.lapots.breed"
version = "1.0-SNAPSHOT"
plugins {
java
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
}
repositories {
mavenCentral()
}
task("execute", JavaExec::class) {
main = "com.lapots.breed.Application"
classpath = sourceSets["main"].runtimeClasspath
}
According the not-listed task - from certain version, Gradle doesn't show custom tasks which don't have assigned AbstractTask.group. You can either list them via gradle tasks --all, or set the group property on the given task(s), e.g.:
task("execute", JavaExec::class) {
group = "myCustomTasks"
main = "com.lapots.breed.Application"
classpath = sourceSets["main"].runtimeClasspath
}

Kotlin Gradle Could not find or load main class

I tried to copy the Spring Boot Kotlin sample project https://github.com/JetBrains/kotlin-examples/tree/master/tutorials/spring-boot-restful. I Added some more dependencies and when I tried to build the executable jar and run it, I got the error:
Could not find or load main class...
Gradle build script:
buildscript {
ext.kotlin_version = '1.1.3' // Required for Kotlin integration
ext.spring_boot_version = '1.5.4.RELEASE'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
}
}
/*plugins {
id 'org.springframework.boot' version '2.0.0.RELEASE'
}*/
apply plugin: 'kotlin' // Required for Kotlin integration
apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-rest-service'
version = '0.1.0'
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.Applicationkt'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin/'
test.java.srcDirs += 'src/test/kotlin/'
}
repositories {
jcenter()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile("org.springframework.boot:spring-boot-starter-web")
compile group: 'org.apache.camel', name: 'camel-quartz2', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-http4', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-docker', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-aws', version: '2.20.2'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Change Applicationkt to ApplicationKt will work, and BTW you may upgrade Kotlin version to 1.3.50.
By Applicationkt I mean the one in this line:
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.Applicationkt'
Kotlin compiles the Application file in two different files:
one file called Application.class with the Springboot things
another file called ApplicationKt.class with the main method
In this second file is where the main function is located at, so you have to use this name in the build.gradle file.
mainClassName = 'org.jetbrains.kotlin.demo.ApplicationKt'
Update your build.gradle to
jar {
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.ApplicationKt'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
with an upper case K in ApplicationKt.
This is required because of the way Kotlin compiles to Java Bytecode. The fun main() function in Kotlin is not attached to any class, but Java always requires a class and does not support classless functions.
The Kotlin compiler has to create a Java class. Because you already defined a class Application it created one with the suffix Kt for the functions in your Kotlin file org/jetbrains/kotlin/demo/Application.kt. You have to set this class so that the JVM can find it.
BTW a Jar file is just a Zip file, you can unpack it and see for yourself if the ApplicationKt.class is there.
For me the main function needed to be outside the class body
#SpringBootApplication
#Configuration
class Application
(private val locationRepository: LocationRepository,
) : CommandLineRunner {
override fun run(vararg args: String?) {
whatever()
}
}
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
Indeed, Kotlin create file ApplicationKt.class in the jar if your main class file is named Application.kt. You have to add the following lines:
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'org.jetbrains.kotlin.demo.ApplicationKt'
If you use the classic jar plugin, you can do as below (which is described in previous responses):
jar {
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.ApplicationKt'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
However, my preference is to use bootJar plugin which is much clear and which allow me to use layered jars for example:
bootJar {
layered() // Not useful if you don't want to use layered jars
}

Why do I need to specify 'from files'?

I was trying to build a jar out of my first groovy script. My project structure is as follows:
- build.gradle
- src\main\groovy\app\Test.groovy
My original gradle script:
apply plugin: 'groovy'
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.11'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
sourceSets.main.groovy.srcDirs = ["src/main/groovy"]
jar {
manifest {
attributes('Main-Class': 'app.Test')
}
}
From the guides I read, this should create a runnable jar. When I try to run it though I always get the error
Error: Could not find or load main class app.Test
I found out now that I need to add these two lines to the jar task:
from files(sourceSets.main.output.classesDir)
from configurations.runtime.asFileTree.files.collect { zipTree(it) }
The weird thing is that if I replace the groovy script with a Test.java class (same content), I don't need those two extra lines to run the jar.
I couldn't find out why I need them or what exactly they do. Can anyone explain that, or offer a documentation link?
I'm new to SO, please help me with my mistakes.
EDIT
The code suggested by tim_yates is translated to test.jar with the following content:
META-INF/MANIFEST.MF
Manifest-Version: 1.0
Main-Class: app.Test
app/Test.class
package app;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import org.codehaus.groovy.runtime.callsite.CallSite;
public class Test implements GroovyObject {
public Test() {
CallSite[] var1 = $getCallSiteArray();
MetaClass var2 = this.$getStaticMetaClass();
this.metaClass = var2;
}
public static void main(String... args) {
CallSite[] var1 = $getCallSiteArray();
var1[0].callStatic(Test.class, "Hi!");
}
}
I execute with the following statement:
java -jar test.jar
Which results in the error message stated above.
You've got to remember that this jar contains Groovy compiled classes. The answer is in your decompiled source that you showed in the beginning. It imports Groovy runtime classes.
If you just run java -jar test.jar those classes are not on the classpath.
Either include groovy on the classpath of your command line or use the gradle application plugin to build a fat JAR (which is probably better for runnable jars) that contain all your application dependencies.
apply plugin: 'groovy'
apply plugin: 'application'
mainClassName='app.Test'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.7'
testCompile 'junit:junit:4.12'
}
task uberjar(type: Jar,dependsOn:[':compileJava',':compileGroovy']) {
from files(sourceSets.main.output.classesDir)
from configurations.runtime.asFileTree.files.collect { zipTree(it) }
manifest {
attributes 'Main-Class': mainClassName
}
}
Then build your jar with gradle uberjar
Assuming Test.groovy looks something like:
package app
class Test {
static main(args) {
println "Hi!"
}
}
Then you only need the following build script:
apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.7'
testCompile 'junit:junit:4.12'
}
jar {
manifest {
attributes('Main-Class': 'app.Test')
}
}

Not able to execute Jbehave with Gradle using Serenity Framewrok

I am using Serenity - JBehave framework. After creation of sample script, I am able to execute Junit runner class from eClipse however when I am trying to execute any of the below command from command prompt it is giving me error.
$gradle clean test aggregate
$gradle clean test
$gradle clean build
The error message is same in all cases, as below:
org.gradle.TestRunnerClass > initializationError FAILED
java.lang.RuntimeException
Caused by: java.lang.RuntimeException
Caused by: java.lang.IllegalArgumentException
Caused by: java.lang.ClassNotFoundException
1 test completed, 1 failed
:test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> There were failing tests. See the report at: file:///C:/$ /build/reports/tests/index.html
Below are the details:
Test Runner class:
package org.gradle;
import net.serenitybdd.jbehave.SerenityStories;
public class TestRunnerClass extends SerenityStories{}
Sample Step Definition class:
package org.gradle.stepDef;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
public class StepDefSticky {
#Given("User is on Sticky note home page")
public void givenUserIsOnStickyNoteHomePage() {
System.out.println("I am in Given");
}
#When("User clicks on Add Note button")
public void whenUserClicksOnAddNoteButton() {
System.out.println("I am in When");
}
#Then("Sticky note pop up should get open")
public void thenStickyNotePopUpShouldGetOpen() {
System.out.println("I am in Then");
}
}
Please see the package structure carefully.
Below is the build.gradle I am using
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'net.serenity-bdd.aggregator'
apply plugin: 'com.jfrog.bintray'
sourceCompatibility = 1.8
version = '1.0'
def poiVersion = "3.10.1"
repositories {
maven { url "repoUrl" }
}
buildscript {
repositories {
maven { url "repoURL" }
}
dependencies {
classpath("net.serenity-bdd:serenity-gradle-plugin:1.0.47")
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:0.6'
classpath 'org.ajoberstar:gradle-git:0.12.0'
}
}
ext {
bintrayBaseUrl = 'https://api.bintray.com/maven'
bintrayRepository = 'maven'
bintrayPackage = 'serenity-cucumber'
projectDescription = 'Serenity Cucumber integration'
if (!project.hasProperty("bintrayUsername")) {
bintrayUsername = 'wakaleo'
}
if (!project.hasProperty("bintrayApiKey")) {
bintrayApiKey = ''
}
serenityCoreVersion = '1.0.47'
cucumberJVMVersion = '1.2.2'
}
dependencies {
testCompile('junit:junit:4.11')
testCompile('org.assertj:assertj-core:1.7.0')
testCompile('org.slf4j:slf4j-simple:1.7.7')
//JBehave jar files
testCompile 'net.serenity-bdd:core:1.0.47'
testCompile 'net.serenity-bdd:serenity-jbehave:1.0.21'
testCompile 'net.serenity-bdd:serenity-junit:1.0.47'
// Apache POI plugin for excel read
compile "org.apache.poi:poi:${poiVersion}"
compile "org.apache.poi:poi-ooxml:${poiVersion}"
compile "org.apache.poi:ooxml-schemas:1.1"
}
gradle.startParameter.continueOnFailure = true
uploadArchives {
repositories { flatDir { dirs 'repos' } }
}
task wrapper(type: Wrapper) { gradleVersion = '2.3' }
I have stored the .story file under the src/test/resources package.
Please help me to understand where I am making mistake. Thanks for your help on this.
Enable standard out and standard error in your build.gradle file:
test {
testLogging {
showStandardStreams = true
}
}
And to make sure all your stories run, add a TestSuite class:
#RunWith(Suite.class)
#SuiteClasses({ Story1.class, Story2.class})
public class TestSuite { }
Note: Story1 & Story2 are the names of the test runners to match a JBehave Gherkin files named Story1.story & Story2.story & step files names Story1Steps.java & Story2Steps.java according to Serenity naming conventions.

Resources