execute JavaExec task using gradle kotlin dsl - gradle

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
}

Related

How can I change my gradle to #public APIs

I got following message when I change from Maven to Gradle.
How can I change to using public apis only?
/*
This file was generated by the Gradle 'init' task.
This project uses #Incubating APIs which are subject to change.
*/
build.gradle.kts:
plugins {
java
`maven-publish`
}
repositories {
mavenLocal()
maven {
url = uri("https://repo.maven.apache.org/maven2/")
}
}
dependencies {
}
group = "org.example"
version = "1.0-SNAPSHOT"
description = ""
java.sourceCompatibility = JavaVersion.VERSION_1_8
publishing {
publications.create<MavenPublication>("maven") {
from(components["java"])
}
}

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).

Gatling is not working with SpringBoot 2.0.1.RELEASE

I'm trying to setup Gatling with Spring Boot 2.0.1.RELEASE.
I've created this api:
#RestController
#RequestMapping("/contact")
public class ContactController {
#GetMapping
public ResponseEntity get() {
return ResponseEntity.ok("Contact retrieved successfully");
}
}
And this basic simulation:
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class ContactSimulation extends Simulation {
val httpConf = http.baseURL("http://localhost:8080")
val scn = scenario("GetContact")
.exec(
http("GetContact")
.get("/contact")
.check(status.is(200))
)
setUp(scn.inject(atOnceUsers(1))).protocols(httpConf)
}
The build.gradle is configured this way:
buildscript {
ext {
springBootVersion = '2.0.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'scala'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.gatling.poc'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('io.gatling.highcharts:gatling-charts-highcharts:2.3.0')
}
task loadTest(type: JavaExec) {
dependsOn testClasses
description = "Load Test With Gatling"
group = "Load Test"
classpath = sourceSets.test.runtimeClasspath
jvmArgs = [
"-Dgatling.core.directory.binaries=${sourceSets.test.output.classesDir.toString()}"
]
main = "io.gatling.app.Gatling"
args = [
"--simulation", "com.gatling.poc.simulations.ContactSimulation",
"--results-folder", "${buildDir}/gatling-results",
"--binaries-folder", sourceSets.test.output.classesDir.toString(),
"--bodies-folder", sourceSets.test.resources.srcDirs.toList().first().toString() + "/gatling/bodies",
]
}
While executing the tests:
./gradlew loadTest
I'm getting the following stacktrace:
21:00:12.804 [main] WARN io.netty.util.concurrent.DefaultPromise - An exception was thrown by org.asynchttpclient.netty.request.NettyRequestSender$1.operationComplete()
java.lang.NoSuchMethodError: io.netty.channel.DefaultChannelId.newInstance()Lio/netty/channel/DefaultChannelId;
at io.netty.channel.AbstractChannel.newId(AbstractChannel.java:111)
at io.netty.channel.AbstractChannel.<init>(AbstractChannel.java:83)
at io.netty.bootstrap.FailedChannel.<init>(FailedChannel.java:33)
at io.netty.bootstrap.AbstractBootstrap.initAndRegister(AbstractBootstrap.java:330)
at io.netty.bootstrap.Bootstrap.doResolveAndConnect(Bootstrap.java:163)
at io.netty.bootstrap.Bootstrap.connect(Bootstrap.java:156)
at org.asynchttpclient.netty.request.NettyChannelConnector.connect0(NettyChannelConnector.java:81)
at org.asynchttpclient.netty.request.NettyChannelConnector.connect(NettyChannelConnector.java:69)
at org.asynchttpclient.netty.request.NettyRequestSender$1.onSuccess(NettyRequestSender.java:292)
at org.asynchttpclient.netty.request.NettyRequestSender$1.onSuccess(NettyRequestSender.java:285)
at org.asynchttpclient.netty.SimpleFutureListener.operationComplete(SimpleFutureListener.java:24)
at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:511)
at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:485)
at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:424)
at io.netty.util.concurrent.DefaultPromise.addListener(DefaultPromise.java:162)
at io.netty.util.concurrent.DefaultPromise.addListener(DefaultPromise.java:33)
at org.asynchttpclient.netty.request.NettyRequestSender.sendRequestWithNewChannel(NettyRequestSender.java:285)
at org.asynchttpclient.netty.request.NettyRequestSender.sendRequestWithCertainForceConnect(NettyRequestSender.java:136)
at org.asynchttpclient.netty.request.NettyRequestSender.sendRequest(NettyRequestSender.java:107)
at org.asynchttpclient.DefaultAsyncHttpClient.execute(DefaultAsyncHttpClient.java:216)
at org.asynchttpclient.DefaultAsyncHttpClient.executeRequest(DefaultAsyncHttpClient.java:184)
at org.asynchttpclient.DefaultAsyncHttpClient.executeRequest(DefaultAsyncHttpClient.java:206)
at io.gatling.http.ahc.HttpEngine.warmpUp(HttpEngine.scala:96)
at io.gatling.http.protocol.HttpProtocol$$anon$1.$anonfun$newComponents$1(HttpProtocol.scala:62)
at io.gatling.core.protocol.ProtocolComponentsRegistry.comps$1(Protocol.scala:67)
at io.gatling.core.protocol.ProtocolComponentsRegistry.$anonfun$components$4(Protocol.scala:69)
at scala.collection.mutable.HashMap.getOrElseUpdate(HashMap.scala:82)
at io.gatling.core.protocol.ProtocolComponentsRegistry.components(Protocol.scala:69)
at io.gatling.http.action.HttpActionBuilder.lookUpHttpComponents(HttpActionBuilder.scala:25)
at io.gatling.http.action.sync.HttpRequestActionBuilder.build(HttpRequestActionBuilder.scala:33)
at io.gatling.core.structure.StructureBuilder.$anonfun$build$1(StructureBuilder.scala:34)
at scala.collection.LinearSeqOptimized.foldLeft(LinearSeqOptimized.scala:122)
at scala.collection.LinearSeqOptimized.foldLeft$(LinearSeqOptimized.scala:118)
at scala.collection.immutable.List.foldLeft(List.scala:86)
at io.gatling.core.structure.StructureBuilder.build(StructureBuilder.scala:33)
at io.gatling.core.structure.StructureBuilder.build$(StructureBuilder.scala:32)
at io.gatling.core.structure.ScenarioBuilder.build(ScenarioBuilder.scala:38)
at io.gatling.core.structure.PopulationBuilder.build(ScenarioBuilder.scala:98)
at io.gatling.core.scenario.SimulationParams.$anonfun$scenarios$1(Simulation.scala:188)
at scala.collection.immutable.List.map(List.scala:283)
at io.gatling.core.scenario.SimulationParams.scenarios(Simulation.scala:188)
at io.gatling.app.Runner.run0(Runner.scala:95)
at io.gatling.app.Runner.run(Runner.scala:64)
at io.gatling.app.Gatling$.start(Gatling.scala:59)
at io.gatling.app.Gatling$.fromArgs(Gatling.scala:43)
at io.gatling.app.Gatling$.main(Gatling.scala:35)
at io.gatling.app.Gatling.main(Gatling.scala)
If I create the same project using SpringBoot 1.5.12.RELEASE, it works perfectly. I'm suspecting of the spring-boot-gradle-plugin since it changes according to the SpringBoot version.
If necessary I can create a project into github to demonstrate the problem. =)
I would appreciate if someone could help me!
I got fix this issue.
The problem was the version of the io.netty group used by the SpringBoot 2.0.1.RELEASE. It is using the version 4.1.23.Final which for some reason (maybe some change in scala) is not executing the gatling tests.
I did the downgrade to use the same version as SpringBoot 1.5.12.RELEASE, which is 4.0.51.Final. I had to add this configuration to the build.gradle:
{
// This build.gradle is the same that I posted above. For the sake of simplicity I just put the configuration that has been necessary to solve the problem.
// After dependencies{} section, I had to put this:
configurations.all {
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'io.netty') {
details.useVersion "4.0.51.Final"
}
}
}
}
}
I don't think is the best solution since I'm reverting the io.netty version to use a older version, which can have some side effect. In my case I didn't have the option of downgrading the SpringBoot version. If you have the option to revert the SpringBoot version, I would recommend to do that.

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

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

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