build.gradle.kts - how to set compiler args correctly? - kotlin

Got the following content:
val commonCompilerArgs = listOfNotNull(
"-Dmicronaut.openapi.views.spec=rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop",
)
tasks {
compileKotlin {
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = commonCompilerArgs
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "11"
}
}
}
But got this error:
Invalid argument: -Dmicronaut.openapi.views.spec=rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop
I guess it is simple, but I don't know how to set this compiler arguments correctly.
Any help appreciated!

If you are using kapt in your Micronaut application gradle scripts then you can set it this way:
kapt {
arguments {
arg(
"micronaut.openapi.views.spec",
"rapidoc.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop"
)
}
}
Open API definition files and Swagger UI are generated during annotation processing phase, where source code and resource files are generated. It means that it is before compileKotlin task.
Part of example build output:
...
> Task :my-app:kaptGenerateStubsKotlin
> Task :my-app:processResources
> Task :my-app:detekt
> Task :my-app:processTestResources NO-SOURCE
> Task :my-app:kaptKotlin
Note: Generating OpenAPI Documentation
Note: Writing OpenAPI YAML to destination: /home/me/prj/my-app/backend/build/tmp/kapt3/classes/main/META-INF/swagger/my-app-1.0.yml
Note: Writing OpenAPI View to destination: /home/me/prj/my-app/backend/build/tmp/kapt3/classes/main/META-INF/swagger/views/swagger-ui/index.html
Note: Creating bean classes for 9 type elements
> Task :my-app:compileKotlin
> Task :my-app:compileJava NO-SOURCE
> Task :my-app:classes
...
Update: You must also add micronaut.router.static-resources section for Swagger into application.yaml configuration file to map swagger static routes like this:
micronaut:
router:
static-resources:
swagger:
paths: classpath:META-INF/swagger
mapping: /swagger/**
swagger-ui:
paths: classpath:META-INF/swagger/views/swagger-ui
mapping: /swagger-ui/**
Then you can access OpenAPI definition file on http://localhost:8080/swagger/my-app-1.0.yml and Swagger UI should be available on http://localhost:8080/swagger-ui .

Related

ktlint not checking kotlin file

I want my project to perform ktlintCheck on all kotlin file, but it only check on build.gradle.kts file.
build.gradle.kts file as below
ktlint {
version.set("9.4.0")
debug.set(true)
verbose.set(true)
android.set(false)
outputToConsole.set(true)
reporters {
reporter(ReporterType.PLAIN)
reporter(ReporterType.CHECKSTYLE)
}
ignoreFailures.set(false)
kotlinScriptAdditionalPaths {
include(fileTree("src/"))
}
filter {
exclude("**/generated/**")
include("**/kotlin/**")
}
}
subprojects {
apply(plugin = "org.jlleitschuh.gradle.ktlint")
ktlint {
debug.set(true)
}
}
When I run gradlew ktlintCheck, the Terminal output as below:
gradlew ktlintCheck
> Task :ktlintKotlinScriptCheck
[DEBUG] Discovered ruleset with " standard" id.
[DEBUG] Discovered reporter with "checkstyle" id.
[DEBUG] Discovered reporter with "json" id.
[DEBUG] Discovered reporter with "html" id.
[DEBUG] Discovered reporter with "plain" id.
[DEBUG] Initializing "plain" reporter with {verbose=true, color=true, color_name=DARK_GRAY}
[DEBUG] Initializing "plain" reporter with {verbose=true, color=true, color_name=DARK_GRAY}, output=C:\Code\XXXX\build\reports\ktlint\ktlintKotlinScriptCheck\ktlintKotlinScriptCheck.txt
[DEBUG] Initializing "checkstyle" reporter with {verbose=true, color=true, color_name=DARK_GRAY}, output=C:\Code\XXXX\build\reports\ktlint\ktlintKotlinScriptCheck\ktlintKotlinScriptCheck.xml
[DEBUG] Checking C:\Code\XXXX\build.gradle.kts
Resolving .editorconfig files for C:\Code\XXXX\build.gradle.kts file path
[DEBUG] 809ms / 1 file(s) / 0 error(s)
To begin there is an error in the configuration of your build.gradle file, in the block Ktlint settings, the line where it appears "version.set (" 9.4.0 ")" is incorrect as well as unnecessary. In any case, if you still decide to use this setting, it should be, for example, version.set ("0.37.2") , since it refers to the Ktlint version and not the jlleitschuh / ktlint-gradle plugin
To solve the problem make the following modifications to the build.gradle.kts file (I use Gradle 6.6.1 with Kotlin DSL in Intellij IDEA community Edition)
Please replace the plugin with the previous version (9.3.0):
build.gradle.kts file in root project
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType // for Ktlint reports
plugins {
kotlin("jvm") version "1.4.10" // Kotlin Compiler
id("org.jetbrains.dokka") version "1.4.10" // Documentation Engine For Kotlin
id("org.jlleitschuh.gradle.ktlint") version "9.3.0" // Kotlin Linter
}
group = "my group" // Replace with your group
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation("org.junit.jupiter:junit-jupiter:5.4.2")
testImplementation(kotlin("test-junit5"))
implementation(kotlin("stdlib-jdk8"))
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.test {
useJUnitPlatform()
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
jvmTarget = "1.8"
}
val compileTestKotlin: KotlinCompile by tasks
compileTestKotlin.kotlinOptions {
jvmTarget = "1.8"
}
ktlint {
// THIS LINE IS NOT necessary and is incorrect -> version.set("9.4.0")
verbose.set(true)
outputToConsole.set(true)
coloredOutput.set(true)
debug.set(false) // in your configuration this option must be set to true
android.set(false)
outputColorName.set("RED")
ignoreFailures.set(false)
enableExperimentalRules.set(false)
reporters {
reporter(ReporterType.CHECKSTYLE)
reporter(ReporterType.JSON)
reporter(ReporterType.HTML)
}
filter {
exclude("**/style-violations.kt")
exclude("**/generated/**")
include("**/kotlin/**")
}
}

Include dependency for custom sourceSet

I have a build.gradle.kts for a small, pure kotlin project (I am aware I am using slightly non-standard source paths):
plugins {
kotlin("jvm") version "1.3.72"
}
repositories { mavenCentral() }
dependencies {
implementation(kotlin("stdlib-jdk8"))
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
sourceSets["main"].java.srcDir("src")
sourceSets["test"].java.srcDirs("test")
sourceSets {
create("demo")?.let {
it.java.srcDir("demo")
// Also tried: it.java.srcDirs("src", "demo")
it.compileClasspath += main.get().output
it.runtimeClasspath += main.get().output
}
}
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
}
listOf("InteractiveClient", "LockingBufferDemo").forEach {
tasks.register<Jar>(it) {
manifest { attributes["Main-Class"] = "${it}Kt" }
from(sourceSets.main.get().output)
from(sourceSets["demo"].output) {
include("**/${it}Kt.class")
}
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get().filter {
it.name.endsWith("jar") }.map { zipTree(it) }
})
}
}
When I try to run one of the "demo" sourceSet based jar tasks ("InteractiveClient" and "LockingBufferDemo"),1 I get a the long list of "Cannot access built-in..." errors indicating the kotlin stdlib is not properly in play.
The actual failing task is compileDemoKotlin, so I tried adding mimetically to the tasks block:
withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
this.kotlinOptions.jvmTarget = "1.8"
}
Which makes no difference.
What's strange to me is that the demo stuff was originally in the test sourceSet, and changing the above back to that (by removing the definition, changing from(sourceSets["demo"]... to from(sourceSets.test... in the jar task(s), and moving the source file) makes the problem disappear. It works.
I don't want this stuff in with automated tests. I imagine I could put them in branches of the main or test set and then use a from() { exclude(... pattern in building the jars,
but that seems awkward and unnecessary.
How do I get a custom source set to compile against the default project dependencies?
See this other recent question of mine about the from(... include( in the jar tasks.
It looks to me like you are missing the configurations that will make the demo source sets use the same dependencies as the main set. Something like this:
configurations["demoImplementation"].extendsFrom(configurations.implementation.get())
configurations["demoRuntimeOnly"].extendsFrom(configurations.runtimeOnly.get())
There is an example in the user guide here that seems to have a very similar use case as yours.
Also, from the issue you created in the Gradle repository, you mentioned it failed with:
Unresolved reference: printlin
I am pretty sure this is a typo of println.
I'm not entirely sure what you're trying to do with your jar files, but I spotted a few problems in your build script:
You have set your source sets like this:
sourceSets["main"].java.srcDir("src")
sourceSets["test"].java.srcDirs("src", "test")
sourceSets {
create("demo")?.let {
it.java.srcDir("demo")
}
}
This means you're supposed the following directory structure:
- <module root>
- src <-- Belongs to both 'main' and a 'test' source sets!
- test <-- Belongs to the 'test' source set
- demo <-- Belongs to the 'demo' source set
As you can see, there's a directory that belongs to two source sets. I'm not sure how this turns out in practice, probably one or the other is discarded. Here's a more standard directory structure:
- <module root>
- src
- main
- test
- demo
You configure it like this:
sourceSets {
main {
java.srcDir("src/main")
}
test {
java.srcDir("src/test")
}
create("demo") {
java.srcDir("src/demo")
}
}
The task compileDemoKotlin actually exists, but you can't access it just like that. If you look at the compileKotlin and compileTestKotlin extension functions source, they look like this:
val TaskContainer.`compileKotlin`: TaskProvider<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
get() = named<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>("compileKotlin")
So the trick is to use named to get the task instead:
named<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>("compileDemoKotlin") {
kotlinOptions.jvmTarget = "1.8"
}
I don't know if that answers your question. If I missed anything please let me know.

Create fat jar from kotlin multiplatform project

I recently switched from old 1.2 multiplatform into 1.3. Difference is, there's one one build.gradle file per multiplatform module (I got 5 of them) so a lot less configuration.
However I can't seem to be able to configure creating runnable fat jar with all dependencies from jvm platform.
I used to use standard "application" plugin in my jvm project and jar task, but that does not work anymore. I found there's "jvmJar" task and I modified it (set Main-class), but created jar doesn't contain dependencies and crashes on ClassNotFoundException. How do I do it?
This is what I have now:
jvm() {
jvmJar {
manifest {
attributes 'Main-Class': 'eu.xx.Runner'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
I did hit that bump and used this work around.
1. Restructure your project
Lets call your project Project.
create another submodule say subA, which will have the gradle notation Project:subA
now, subA has your multiplatform code in it (It is the gradle project with apply :kotlin-multiplafrom) in its build.gradle
2. Add Another submodule
create another submodule which targets only jvm say subB, which will have the gradle notation Project:subB
So, subB will have plugins: 'application' and 'org.jetbrains.kotlin.jvm'
3. Add your module as a gradle dependency (see my build.gradle)
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.3.31'
id "application"
}
apply plugin: "kotlinx-serialization"
group 'tz.or.self'
version '0.0.0'
mainClassName = "com.example.MainKt"
sourceCompatibility = 1.8
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
dependencies {
implementation project(':subA')
}
you can proceed and build subB as you would a regular java project or even use the existing plugins, it will work
Got it working with the multiplatform plugin in kotlin 1.3.61:
The following works for a main file in src/jvmMain/kotlin/com/example/Hello.kt
Hello.kt must also specify its package as package com.example
I configured my jvm target in this way:
kotlin {
targets {
jvm()
configure([jvm]) {
withJava()
jvmJar {
manifest {
attributes 'Main-Class': 'com.example.HelloKt'
}
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
}
}
Got it to work with a slightly modified version of what luca992 did:
kotlin {
jvm() {
withJava()
jvmJar {
manifest {
attributes 'Main-Class': 'sample.MainKt'
}
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
...
}
The only way to get gradle/multiplatform working appears to be endless trial and error; It's a nightmare, it's not being built as a "build" system so much as a "build system"; to put it another way, these two tools (together or in isolation) are a means of implementing only a single software development life cycle that the plugin maker intended, however, if you've engineered a desired software lifecycle and CI/CD system and now your trying to implement that engineering, it will be MUCH harder to do it with these tools than it would be to do it with scripts, code or maven. There are a number of reasons for this:
Massive changing in coding convention due to the plugin makers only exposing bar minimum configurability, probably only giving access to the things they need for their own personal project.
Very poor documentation updates; Kotlin, gradle and plugins are changing so rapidly I have begun to seriously question the usefulness of these tools.
Thus, at the time of writing this seems to be the correct syntax to use when using kotlin 1.3.72, multiplatform 1.3.72, ktor 1.3.2 and gradle 6.2.2 (using the kts format).
Note the fatJar seems to assemble correctly but won't run, it can't find the class, so I included the second runLocally task I've been using in the mean time.
This isn't a complete solution so I hate posting it on here, but from what I can tell... it is the most complete and up to date solution I can find documented anywhere.
//Import variables from gradle.properties
val environment: String by project
val kotlinVersion: String by project
val ktorVersion: String by project
val kotlinExposedVersion: String by project
val mySqlConnectorVersion: String by project
val logbackVersion: String by project
val romeToolsVersion: String by project
val klaxonVersion: String by project
val kotlinLoggingVersion: String by project
val skrapeItVersion: String by project
val jsoupVersion: String by project
val devWebApiServer: String by project
val devWebApiServerVersion: String by project
//Build File Configuration
plugins {
java
kotlin("multiplatform") version "1.3.72"
}
group = "com.app"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
jcenter()
jcenter {
url = uri("https://kotlin.bintray.com/kotlin-js-wrappers")
}
maven {
url = uri("https://jitpack.io")
}
}
//Multiplatform Configuration
kotlin {
jvm {
compilations {
val main = getByName("main")
tasks {
register<Jar>("buildFatJar") {
group = "application"
manifest {
attributes["Implementation-Title"] = "Gradle Jar File Example"
attributes["Implementation-Version"] = archiveVersion
attributes["Main-Class"] = "com.app.BackendAppKt"
}
archiveBaseName.set("${project.name}-fat")
from(main.output.classesDirs, main.compileDependencyFiles)
with(jar.get() as CopySpec)
}
register<JavaExec>("runLocally") {
group = "application"
setMain("com.app.BackendAppKt")
classpath = main.output.classesDirs
classpath += main.compileDependencyFiles
}
}
}
}
js {
browser { EXCLUDED FOR LENGTH }
}
sourceSets { EXCLUDED FOR LENGTH }
}

How to run Karate and Gatling with Gradle build system

I'm trying to run a Karate test as a Gatling performance test. My entire setup works perfect when using Maven. I am being forced to use Gradle however. When trying to run under Gradle the below disaster unfolds.
Appreciate any ideas what might be causing KarateAction to crash.
MyAPI.scala
class MyAPI extends Simulation {
val protocol = karateProtocol(
"/myendpoint" -> Nil
)
val action = karateFeature("classpath:org/mycompany/karate/tests/myAPI.feature#test=myTag")
setUp(
scenario("my-api")
.exec(action)
.inject(rampUsersPerSec(1) to (5) during (5 seconds))
.protocols(protocol)
)
}
build.gradle
buildscript {
ext {
karateVersion = '0.9.2'
}
}
apply plugin: 'scala'
configurations {
gatling
}
dependencies {
testCompile("com.intuit.karate:karate-apache:${karateVersion}")
testCompile("com.intuit.karate:karate-mock-servlet:${karateVersion}")
testCompile("com.intuit.karate:karate-junit4:${karateVersion}")
testCompile("com.intuit.karate:karate-gatling:${karateVersion}")
testCompile("net.masterthought:cucumber-reporting:3.8.0")
gatling "org.scala-lang:scala-library:2.12.8"
gatling "io.gatling:gatling-app:3.0.2"
gatling "io.gatling.highcharts:gatling-charts-highcharts:3.0.2"
gatling "com.intuit.karate:karate-gatling:${karateVersion}"
}
sourceSets {
simulations {
scala {
srcDirs = ['src/test/java/org/mycompany/karate/perf']
}
resources {
srcDirs = ['src/test/java/org/mycompany/karate/perf']
}
compileClasspath += configurations.gatling
}
test {
resources {
srcDir file('src/test/java')
exclude '**/*.java'
}
}
}
test {
systemProperty "karate.options", System.properties.getProperty("karate.options")
systemProperty "karate.env", System.properties.getProperty("karate.env")
outputs.upToDateWhen { false }
}
task gatlingRun(type: JavaExec) {
description = 'Run Gatling Tests'
new File("${buildDir}/reports/gatling").mkdirs()
classpath = sourceSets.simulations.runtimeClasspath += configurations.gatling
main = "io.gatling.app.Gatling"
args = [
'-s', 'org.mycompany.karate.perf.MyAPI',
'-sf', 'src/test/java/org/mycompany/karate/perf',
'-rf', "${buildDir}/reports/gatling"
]
systemProperties System.properties
}
command line
gradle gatlingRun
command line output
> Task :compileSimulationsJava NO-SOURCE
> Task :compileSimulationsScala
Pruning sources from previous analysis, due to incompatible CompileSetup.
there were 6 feature warnings; re-run with -feature for details
one warning found
> Task :processSimulationsResources NO-SOURCE
> Task :simulationsClasses
> Task :gatlingRun
16:40:27.238 [main] INFO io.gatling.core.config.GatlingConfiguration$ - Gatling will try to use 'gatling.conf' as custom config file.
16:40:27.598 [GatlingSystem-akka.actor.default-dispatcher-3] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
16:40:28.242 [GatlingSystem-akka.actor.default-dispatcher-3] INFO io.gatling.core.stats.writer.ConsoleDataWriter - Initializing
16:40:28.242 [GatlingSystem-akka.actor.default-dispatcher-4] INFO io.gatling.core.stats.writer.LogFileDataWriter - Initializing
16:40:28.248 [GatlingSystem-akka.actor.default-dispatcher-3] INFO io.gatling.core.stats.writer.ConsoleDataWriter - Initialized
16:40:28.253 [GatlingSystem-akka.actor.default-dispatcher-4] INFO io.gatling.core.stats.writer.LogFileDataWriter - Initialized
Simulation org.mycompany.karate.perf.MyAPI started...
16:40:28.359 [GatlingSystem-akka.actor.default-dispatcher-2] ERROR com.intuit.karate.gatling.KarateAction - 'classpath:org/mycompany/karate/tests/myAPI.feature#test=myTag' crashed on session Session(my-api,1,1558395628341,Map(),0,OK,List(),io.gatling.core.protocol.ProtocolComponentsRegistry$$Lambda$329/1759250827#7cee98de), forwarding to the next one
java.lang.NullPointerException: null
at com.intuit.karate.Resource.<init>(Resource.java:55)
at com.intuit.karate.core.FeatureParser.parse(FeatureParser.java:75)
at com.intuit.karate.FileUtils.parseFeatureAndCallTag(FileUtils.java:155)
at com.intuit.karate.Runner.callAsync(Runner.java:183)
at com.intuit.karate.gatling.KarateAction.execute(KarateAction.scala:77)
at io.gatling.core.action.Action.$bang(Action.scala:38)
at io.gatling.core.action.Action.$bang$(Action.scala:38)
at com.intuit.karate.gatling.KarateAction.io$gatling$core$action$ChainableAction$$super$$bang(KarateAction.scala:37)
at io.gatling.core.action.ChainableAction.$bang(Action.scala:63)
at io.gatling.core.action.ChainableAction.$bang$(Action.scala:61)
at com.intuit.karate.gatling.KarateAction.io$gatling$core$action$ExitableAction$$super$$bang(KarateAction.scala:37)
at io.gatling.core.action.ExitableAction.$bang(BlockExit.scala:138)
at io.gatling.core.action.ExitableAction.$bang$(BlockExit.scala:136)
at com.intuit.karate.gatling.KarateAction.$bang(KarateAction.scala:37)
at io.gatling.core.controller.inject.Workload.startUser(Workload.scala:55)
at io.gatling.core.controller.inject.Workload.injectUser(Workload.scala:64)
at io.gatling.core.controller.inject.open.OpenWorkload.$anonfun$injectBatch$1(OpenWorkload.scala:35)
at io.gatling.core.controller.inject.open.OpenWorkload.$anonfun$injectBatch$1$adapted(OpenWorkload.scala:35)
at io.gatling.core.controller.inject.open.UserStream.withStream(UserStream.scala:58)
at io.gatling.core.controller.inject.open.OpenWorkload.injectBatch(OpenWorkload.scala:35)
at io.gatling.core.controller.inject.Injector.$anonfun$inject$1(Injector.scala:60)
at io.gatling.core.controller.inject.Injector.$anonfun$inject$1$adapted(Injector.scala:59)
at scala.collection.Iterator.foreach(Iterator.scala:941)
at scala.collection.Iterator.foreach$(Iterator.scala:941)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
at scala.collection.MapLike$DefaultValuesIterable.foreach(MapLike.scala:213)
at io.gatling.core.controller.inject.Injector.io$gatling$core$controller$inject$Injector$$inject(Injector.scala:59)
at io.gatling.core.controller.inject.Injector$$anonfun$1.applyOrElse(Injector.scala:92)
at io.gatling.core.controller.inject.Injector$$anonfun$1.applyOrElse(Injector.scala:82)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:38)
at akka.actor.FSM.processEvent(FSM.scala:684)
at akka.actor.FSM.processEvent$(FSM.scala:681)
at io.gatling.core.controller.inject.InjectorFSM.processEvent(InjectorFSM.scala:37)
at akka.actor.FSM.akka$actor$FSM$$processMsg(FSM.scala:678)
at akka.actor.FSM$$anonfun$receive$1.applyOrElse(FSM.scala:672)
at akka.actor.Actor.aroundReceive(Actor.scala:517)
at akka.actor.Actor.aroundReceive$(Actor.scala:515)
at io.gatling.core.akka.BaseActor.aroundReceive(BaseActor.scala:24)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:588)
at akka.actor.ActorCell.invoke(ActorCell.scala:557)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:258)
at akka.dispatch.Mailbox.run(Mailbox.scala:225)
at akka.dispatch.Mailbox.exec(Mailbox.scala:235)
at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
16:40:28.359 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.action.Exit - End user #1
16:40:28.360 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.open.OpenWorkload - Start user #1
16:40:28.363 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.open.OpenWorkload - Injecting 4 users in scenario my-api, continue=true
16:40:28.364 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.Injector - End user #1
16:40:29.347 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.open.OpenWorkload - Injecting 0 users in scenario my-api, continue=true
16:40:29.373 [GatlingSystem-akka.actor.default-dispatcher-2] ERROR com.intuit.karate.gatling.KarateAction - 'classpath:org/mycompany/karate/tests/myAPI.feature#test=myTag' crashed on session Session(my-api,2,1558395629372,Map(),0,OK,List(),io.gatling.core.protocol.ProtocolComponentsRegistry$$Lambda$329/1759250827#7cee98de), forwarding to the next one
I have a gradle project with scala and java, and had to create a gradle task to move resources to the right folder, in order to make them available.
task copyResources(type: Copy) {
from ("src/test/java/") {
include "/**/*.feature"
include "karate-config*.js"
include "logback*.xml"
include "/**/*.csv"
include "/**/*.json"
}
into "$buildDir/classes/java/test/"
}
This is just a guess.
Your build.gradle defines src/test/java as resource folder:
test {
resources {
srcDir file('src/test/java')
exclude '**/*.java'
}
}
The karate gatling demo defines src/test/scala as resource folder.
This is necessary, because otherwise the *.feature files next to your scala/java source files are not treated as part of the resulting artifact.
Furthermore, you are using the classpath of the simulation source set when running gatling test. Make sure, that your *.feature are included in that classpath.
As an alternative, you can put your *.feature files under src/test/resources/com/your/package, but this increases "the distance" between your feature and source code files.
Debugging Hint:
Print the file tree of your build/resources folder in order to check whether or not the feature files are included in the resulting build artifact and that the path matches the path you are referencing in your runner.
Let me know if this was useful!

How to create a fat JAR with Gradle Kotlin script?

As titled, I'd like to know how to modify the gradle.build.kts in order to have a task to create a unique jar with all the dependencies (kotlin lib included) inside.
I found this sample in Groovy:
//create a single Jar with all dependencies
task fatJar(type: Jar) {
manifest {
attributes 'Implementation-Title': 'Gradle Jar File Example',
'Implementation-Version': version,
'Main-Class': 'com.mkyong.DateUtils'
}
baseName = project.name + '-all'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
But I have no idea how I could write that in kotlin, other than:
task("fatJar") {
}
Here is a version that does not use a plugin, more like the Groovy version.
import org.gradle.jvm.tasks.Jar
val fatJar = task("fatJar", type = Jar::class) {
baseName = "${project.name}-fat"
manifest {
attributes["Implementation-Title"] = "Gradle Jar File Example"
attributes["Implementation-Version"] = version
attributes["Main-Class"] = "com.mkyong.DateUtils"
}
from(configurations.runtime.map({ if (it.isDirectory) it else zipTree(it) }))
with(tasks["jar"] as CopySpec)
}
tasks {
"build" {
dependsOn(fatJar)
}
}
Also explained here
Some commenters pointed out that this does not work anymore with newer Gradle versions.
Update tested with Gradle 5.4.1:
import org.gradle.jvm.tasks.Jar
val fatJar = task("fatJar", type = Jar::class) {
baseName = "${project.name}-fat"
manifest {
attributes["Implementation-Title"] = "Gradle Jar File Example"
attributes["Implementation-Version"] = version
attributes["Main-Class"] = "com.mkyong.DateUtils"
}
from(configurations.runtimeClasspath.get().map({ if (it.isDirectory) it else zipTree(it) }))
with(tasks.jar.get() as CopySpec)
}
tasks {
"build" {
dependsOn(fatJar)
}
}
Note the difference in configurations.runtimeClasspath.get() and with(tasks.jar.get() as CopySpec).
Here are 4 ways to do this. Note that the first 3 methods modify the existing Jar task of Gradle.
Method 1: Placing library files beside the result JAR
This method does not need application or any other plugins.
tasks.jar {
manifest.attributes["Main-Class"] = "com.example.MyMainClass"
manifest.attributes["Class-Path"] = configurations
.runtimeClasspath
.get()
.joinToString(separator = " ") { file ->
"libs/${file.name}"
}
}
Note that Java requires us to use relative URLs for the Class-Path attribute. So, we cannot use the absolute path of Gradle dependencies (which is also prone to being changed and not available on other systems). If you want to use absolute paths, maybe this workaround will work.
Create the JAR with the following command:
./gradlew jar
The result JAR will be created in build/libs/ directory by default.
After creating your JAR, copy your library JARs in libs/ sub-directory of where you put your result JAR. Make sure your library JAR files do not contain space in their file name (their file name should match the one specified by ${file.name} variable above in the task).
Method 2: Embedding the libraries in the result JAR file (fat or uber JAR)
This method too does not need any Gradle plugin.
tasks.jar {
manifest.attributes["Main-Class"] = "com.example.MyMainClass"
val dependencies = configurations
.runtimeClasspath
.get()
.map(::zipTree) // OR .map { zipTree(it) }
from(dependencies)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
Creating the JAR is exactly the same as the previous method.
Method 3: Using the Shadow plugin (to create a fat or uber JAR)
plugins {
id("com.github.johnrengelman.shadow") version "6.0.0"
}
// Shadow task depends on Jar task, so these configs are reflected for Shadow as well
tasks.jar {
manifest.attributes["Main-Class"] = "org.example.MainKt"
}
Create the JAR with this command:
./gradlew shadowJar
See Shadow documentations for more information about configuring the plugin.
Method 4: Creating a new task (instead of modifying the Jar task)
tasks.create("MyFatJar", Jar::class) {
group = "my tasks" // OR, for example, "build"
description = "Creates a self-contained fat JAR of the application that can be run."
manifest.attributes["Main-Class"] = "com.example.MyMainClass"
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
val dependencies = configurations
.runtimeClasspath
.get()
.map(::zipTree)
from(dependencies)
with(tasks.jar.get())
}
Running the created JAR
java -jar my-artifact.jar
The above solutions were tested with:
Java 17
Gradle 7.1 (which uses Kotlin 1.4.31 for .kts build scripts)
See the official Gradle documentation for creating uber (fat) JARs.
For more information about manifests, see Oracle Java Documentation: Working with Manifest files.
For difference between tasks.create() and tasks.register() see this post.
Note that your resource files will be included in the JAR file automatically (assuming they were placed in /src/main/resources/ directory or any custom directory set as resources root in the build file). To access a resource file in your application, use this code (note the / at the start of names):
Kotlin
val vegetables = MyClass::class.java.getResource("/vegetables.txt").readText()
// Alternative ways:
// val vegetables = object{}.javaClass.getResource("/vegetables.txt").readText()
// val vegetables = MyClass::class.java.getResourceAsStream("/vegetables.txt").reader().readText()
// val vegetables = object{}.javaClass.getResourceAsStream("/vegetables.txt").reader().readText()
Java
var stream = MyClass.class.getResource("/vegetables.txt").openStream();
// OR var stream = MyClass.class.getResourceAsStream("/vegetables.txt");
var reader = new BufferedReader(new InputStreamReader(stream));
var vegetables = reader.lines().collect(Collectors.joining("\n"));
Here is how to do it as of Gradle 6.5.1, Kotlin/Kotlin-Multiplatform 1.3.72, utilizing a build.gradle.kts file and without using an extra plugin which does seem unnecessary and problematic with multiplatform;
Note: in reality, few plugins work well with the multiplatform plugin from what I can tell, which is why I suspect its design philosophy is so verbose itself. It's actually fairly elegant IMHO, but not flexible or documented enough so it takes a ton of trial and error to setup even WITHOUT additional plugins.
Hope this helps others.
kotlin {
jvm {
compilations {
val main = getByName("main")
tasks {
register<Jar>("fatJar") {
group = "application"
manifest {
attributes["Implementation-Title"] = "Gradle Jar File Example"
attributes["Implementation-Version"] = archiveVersion
attributes["Main-Class"] = "[[mainClassPath]]"
}
archiveBaseName.set("${project.name}-fat")
from(main.output.classesDirs, main.compileDependencyFiles)
with(jar.get() as CopySpec)
}
}
}
}
}
You could use the ShadowJar plugin to build a fat jar:
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
buildscript {
repositories {
mavenCentral()
gradleScriptKotlin()
}
dependencies {
classpath(kotlinModule("gradle-plugin"))
classpath("com.github.jengelman.gradle.plugins:shadow:1.2.3")
}
}
apply {
plugin("kotlin")
plugin("com.github.johnrengelman.shadow")
}
repositories {
mavenCentral()
}
val shadowJar: ShadowJar by tasks
shadowJar.apply {
manifest.attributes.apply {
put("Implementation-Title", "Gradle Jar File Example")
put("Implementation-Version" version)
put("Main-Class", "com.mkyong.DateUtils")
}
baseName = project.name + "-all"
}
Simply run the task with 'shadowJar'.
NOTE: This assumes you're using GSK 0.7.0 (latest as of 02/13/2017).