how to solve kotlin coroutine annotation warning - kotlin

let me ask
I use kotlin coroutine
#OptIn(DelicateCoroutinesApi::class)
GlobalScope.launch {
displaySura()
}
and in the build tab showing warning:
This annotation should be used with the compiler argument '-opt-in=kotlin.RequiresOptIn'
how to solve this warning?
thanks in advance

You can add -opt-in=kotlin.RequiresOptIn compiler argument in the build file:
compileKotlin {
kotlinOptions {
freeCompilerArgs += [
"-Xopt-in=kotlin.RequiresOptIn"
]
}
}

To clarify to #Sergio's answer, you can add the block here in your app's build.gradle file
android {
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs += [
"-Xopt-in=kotlin.RequiresOptIn"
]
}

Related

Building Kotlin TornadoFx into exe for Windows

I have an application written in Kotlin and I used TornadoFx to build a GUI around it. As stated in the TornadoFx guide, I used OpenJDK11 and set kotlin.jvmtarget to "11". Here is my gradle build:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.4.30'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.9'
id 'java'
id 'edu.sc.seis.launch4j' version '2.4.9'
}
group = 'me.nicola'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
application {
mainClassName = "Engine"
}
javafx {
version = "11.0.2"
modules = ['javafx.controls', 'javafx.graphics']
}
dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
implementation 'no.tornado:tornadofx:1.7.20'
implementation group: 'org.apache.commons', name: 'commons-email', version: '1.5'
implementation 'com.github.doyaaaaaken:kotlin-csv-jvm:0.15.0'
}
test {
useJUnit()
}
jar {
manifest {
attributes "Main-Class" : "EngineKt"
}
}
compileKotlin {
kotlinOptions.jvmTarget = "11"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "11"
}
task fatJar(type: Jar) {
baseName 'PrimaNotaHelper'
manifest {
attributes "Main-Class": "EngineKt"
}
from {
configurations.runtimeClasspath.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
launch4j {
mainClassName = 'EngineKt'
//icon = "${projectDir}/icons/myApp.ico"
}
I'm trying to use Launch4J to bundle my app into an executable for windows (.exe) and it compiles correctly when I launch the "launch4j" task, building the "lib" folder and the exe file. However, once I'm on Windows the executable does not work.
I also tried to use the Launch4J GUI for Windows and played around a little bit with that but nothing works for me: either It simply crash before starting or ask me for a different version of the JRE.
Can someone help me to set up my build correctly?
Thank you so much!

IntelliJ IDEA does not find candidates for kotlinOptions property but project works fine

I always create Kotlin projects with Gradle: File -> New -> Project -> Gradle -> Kotlin/JVM.
The project works fine, however, IntelliJ IDEA highlights this part of the code:
build.gradle false warning
Is there a way to remove this warning?
This is the entire build.gradle file:
plugins {
id "java"
id "org.jetbrains.kotlin.jvm" version "$kotlinVersion"
}
group "com.alelad"
version "1.0-SNAPSHOT"
allprojects {
apply plugin: "java"
apply plugin: "org.jetbrains.kotlin.jvm"
repositories {
mavenCentral()
jcenter()
}
dependencies {}
compileKotlin {
kotlinOptions {
jvmTarget = "13"
allWarningsAsErrors = true
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "13"
allWarningsAsErrors = true
}
}
}
Just remove compileKotlin and compileTestKotlin all together. They are deprecated now and your project should work just fine without them. That's what I'm doing and everything works great in all my projects.

How to add coverage report (JaCoCo) to kotest based using build.gradle.kts?

I use Kotlin for server side, and I want to add test coverage (by using JaCoCo but can be any other open source).
At the moment, I don't find any documentation to explain how to enable/add coverage report to kotlin project based on kotest which actually works.
(Yes I tried the official documentation)
build.gradle.kts:
import Libraries.coroutines
import Libraries.koTest
import Libraries.koTestCore
import Libraries.mockk
import Libraries.testcontainers
import Libraries.testcontainersPostgres
plugins {
java
`kotlin-dsl` version "1.3.5" apply false
kotlin("jvm") version Versions.kotlin_version
kotlin("plugin.serialization") version Versions.kotlin_version apply false
id("com.diffplug.gradle.spotless") version Plugins.spotless
id("com.palantir.docker") version Plugins.docker apply false
id("com.palantir.docker-run") version Plugins.docker apply false
id("com.google.protobuf") version Plugins.protobuf apply false
id("org.flywaydb.flyway") version Plugins.flyway apply false
}
allprojects {
group = "my-app"
version = "2.0"
apply(plugin = "kotlin")
apply(plugin = "com.diffplug.gradle.spotless")
repositories {
mavenCentral()
jcenter()
}
tasks {
compileKotlin {
dependsOn(spotlessApply)
kotlinOptions {
jvmTarget = "11"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "11"
}
}
}
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
tasks.withType<Test> {
useJUnitPlatform()
maxParallelForks = 1
environment("ENV", "test")
}
afterEvaluate {
project.configurations.forEach {
// Workaround the Gradle bug resolving multiplatform dependencies.
if (it.name.contains("Proto")) {
it.attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class.java, Usage.JAVA_RUNTIME))
}
}
}
}
subprojects {
spotless {
kotlin {
ktlint().userData(mapOf("disabled_rules" to "no-wildcard-imports"))
trimTrailingWhitespace()
endWithNewline()
}
}
dependencies {
implementation(coroutines)
testImplementation(koTest)
testImplementation(koTestCore)
testImplementation(mockk)
testImplementation(testcontainers)
testImplementation(testcontainersPostgres)
}
configurations {
all {
resolutionStrategy.setForcedModules("org.apache.httpcomponents:httpclient:4.5.9")
}
}
}
Any help will be great. Thanks in advance.
in my experience, Jacoco and Kotest interoperate just fine out of the box. I'm using it and all I need to do is the following:
plugins {
jacoco
// The rest of your plugins
}
// Your build, as it was before
You can inspect a working Jacoco + Kotest build here.
To verify that it works, you can e.g., feed the Jacoco generated data to services such as Codecov.io.
First, generate the report in XML format:
tasks.jacocoTestReport {
reports {
xml.isEnabled = true
}
}
And then use the Codecov.io service to fetch and analyze the results:
bash <(curl -s https://codecov.io/bash)
As you can see in this report, Jacoco is doing its job without further configuration.

Receiving form params to Ktor server

I'm new to Java and Kotlin, trying to build a contact form with Ktor, so I enabled the insecure connection of my gmail from here, and built the app below:
blogApp.kt:
package blog
import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
import org.apache.commons.mail.*
fun Application.module() {
install(DefaultHeaders)
install(CallLogging)
install(Routing) {
get("/") {
call.respondText("""
My Example Blog2
<form action="/contact-us" method="post">
<input name="subject" placeholder="Subject">
<br>
<textarea name="message" placeholder="Your message ..."></textarea>
<br>
<button>Submit</button>
</form>
""", ContentType.Text.Html)
}
post("/contact-us") {
SimpleEmail().apply {
setHostName("smtp.gmail.com")
setSmtpPort(465)
setAuthenticator(DefaultAuthenticator("my_alias#gmail.com", "my_gmil_passoword"))
setSSLOnConnect(true)
setFrom("my_alias#gmail.com")
setSubject("subject") // I need to use formParam
setMsg("message") // I need to use formParam
addTo("my_alias#gmail.com")
}.send() // will throw email-exception if something is wrong
call.respondRedirect("/contact-us/success")
}
get("/contact-us/success") {
call.respondText("Your message was sent", ContentType.Text.Html)
}
}
}
fun main(args: Array<String>) {
embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
}
build.gradle:
group 'Example'
version 'alpha'
buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
sourceCompatibility = 1.8
ext.ktor_version = '0.4.0'
repositories {
mavenCentral()
maven { url "http://dl.bintray.com/kotlin/ktor" }
maven { url "https://dl.bintray.com/kotlin/kotlinx" }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
compile "org.jetbrains.ktor:ktor-core:$ktor_version"
compile "org.jetbrains.ktor:ktor-netty:$ktor_version"
compile "org.apache.commons:commons-email:1.4"
compile "org.slf4j:slf4j-simple:1.7.25"
compile "ch.qos.logback:logback-classic:1.2.1"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
kotlin {
experimental {
coroutines "enable"
}
}
jar {
baseName 'abc'
manifest {
attributes 'Main-Class': 'blog.BlogAppKt'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
and things gone smoothly with it, I was able to send an email to myself then redirect to the success page, but the message got sent is with pre-set data:
setSubject("subject") // I need to use formParam
setMsg("message") // I need to use formParam
how can I make the Ktor receive the data the user really entered in the form, how can I read the form params?
You can use call.receive<ValuesMap>() and introspect the data:
import org.jetbrains.ktor.request.* // for recieve
import org.jetbrains.ktor.util.* // for ValuesMap
post("/contact-us") {
val post = call.receive<ValuesMap>()
val subj = post["subject"]
val msg = post["message"]
SimpleEmail().apply { ... }
}
NOTE: ValuesMap is deprecated in latest ktor version, so use the following code:
val post = call.receiveParameters()
Well although the above answer would have been correct at that point of time, today when I am going through kotlin + Ktor, I see that the above answer is not valid anymore.
What you need now is something like this:
call.receive< Parameters >()["PARAM_NAME"]
Parameters class is in the following package: io.ktor.http.Parameters
Nikhil

Failed resolution of: Lcom/dropbox/chooser/android/R$layout;

I got a problem when I want to build jar file dropbox. It's alway show the error
" E/AndroidRuntime(24171): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/dropbox/chooser/android/R$layout;" when I import dropboxchoosersdk.jar instead of all lib DropboxChooserSDK
It's run well when I reference all lib DropboxChooserSDK.
So I would like to build jar file Dropbox to setup auto build with gradle. Anyone got the same problem, please help me. Thank you.
I found the problem that we need follow some steps :
- Try to clean gradle build "gradle clean build" in terminal.
- Then we config the gradle setting file missing.
lintOptions {
abortOnError false
}
Here is my gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.10.+'
}
}
apply plugin: 'android-library'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile 'com.android.support:support-v4:13.0.+'
}
android {
lintOptions {
abortOnError false
}
compileSdkVersion 19
buildToolsVersion '19.1.0'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}