java.lang.UnsupportedOperationException: Packages and file facades are not yet supported in Kotlin reflection - kotlin

When starting a basic Ktor app, I get:
Exception in thread "main" java.lang.UnsupportedOperationException: Packages and file facades are not yet supported in Kotlin reflection. Meanwhile please use Java reflection to inspect this class: class com.example.ApplicationKt
at kotlin.reflect.jvm.internal.KClassImpl.reportUnresolvedClass(KClassImpl.kt:301)
at kotlin.reflect.jvm.internal.KClassImpl.access$reportUnresolvedClass(KClassImpl.kt:43)
at kotlin.reflect.jvm.internal.KClassImpl$Data$descriptor$2.invoke(KClassImpl.kt:53)
at kotlin.reflect.jvm.internal.KClassImpl$Data$descriptor$2.invoke(KClassImpl.kt:44)
at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(ReflectProperties.java:92)
at kotlin.reflect.jvm.internal.ReflectProperties$Val.getValue(ReflectProperties.java:31)
at kotlin.reflect.jvm.internal.KClassImpl$Data.getDescriptor(KClassImpl.kt)
at kotlin.reflect.jvm.internal.KClassImpl$Data$objectInstance$2.invoke(KClassImpl.kt:106)
at kotlin.reflect.jvm.internal.ReflectProperties$LazyVal.invoke(ReflectProperties.java:62)
at kotlin.reflect.jvm.internal.ReflectProperties$Val.getValue(ReflectProperties.java:31)
at kotlin.reflect.jvm.internal.KClassImpl$Data.getObjectInstance(KClassImpl.kt)
at kotlin.reflect.jvm.internal.KClassImpl.getObjectInstance(KClassImpl.kt:239)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createModuleContainer(ApplicationEngineEnvironmentReloading.kt:328)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:317)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:275)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:127)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:247)
at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:106)
at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:18)
at io.ktor.server.engine.ApplicationEngine$DefaultImpls.start$default(ApplicationEngine.kt:52)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:17)
at com.example.ApplicationKt.main(Application.kt:10)
The app is just:
fun main(args: Array<String>): Unit = EngineMain.main(args)
fun Application.demoModule() {
routing {
get("/") {
call.respondText("Hello ${call.parameters["name"]}")
}
}
}

I just noticed the file resources.application.conf had an issue.
It had the wrong module name. I changed com.example.ApplicationKt.module to com.example.ApplicationKt.demoModule:
ktor {
deployment {
port = 8080
port = ${?PORT}
}
application {
modules = [ com.example.ApplicationKt.demoModule ]
}
}
What's annoying is that the error help says nothing about it.

Related

Ktor client NoSuchMethodError

I want to write a telegram bot and use this library from Github for that. In this telegram bot I need to make some requests to another service, so I want to use the ktor client library for that. However when I try to instantiate the ktor httpClient I get the following exception:
Exception in thread "main" java.lang.NoSuchMethodError: 'void io.ktor.util.collections.ConcurrentMap.<init>(io.ktor.util.Lock, int, int, kotlin.jvm.internal.DefaultConstructorMarker)'
at io.ktor.client.engine.cio.CIOEngine.<init>(CIOEngine.kt:32)
at io.ktor.client.engine.cio.CIO.create(CIOCommon.kt:23)
at io.ktor.client.HttpClientKt.HttpClient(HttpClient.kt:42)
at io.ktor.client.HttpClientJvmKt.HttpClient(HttpClientJvm.kt:21)
at io.ktor.client.HttpClientJvmKt.HttpClient$default(HttpClientJvm.kt)
at problem.ktor.MainKt.main(Main.kt:9)
at problem.ktor.MainKt.main(Main.kt)
I made a new project and narrowed the problem down to the telegram bot library, which apparently conflicts with the kotr library. I assume some version conflict of the kotr library, because that's where the exception happens. How can I solve the conflict?
Here is a minimal reproducible example. Use the following build.gradle.kts file:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
application
kotlin("jvm") version "1.4.30"
}
repositories {
mavenCentral()
maven(url = "https://jitpack.io")
}
dependencies {
implementation("io.ktor:ktor-client-core:1.5.2")
implementation("io.ktor:ktor-client-cio:1.5.2")
implementation("com.github.kotlin-telegram-bot:kotlin-telegram-bot:6.0.4")
}
And run the following minimal main function:
import io.ktor.client.*
fun main() {
HttpClient()
}
Maybe it's important, I use Java 15.0.2.
The problematic dependency is com.github.kotlin-telegram-bot.kotlin-telegram-bot:webhook:6.0.4. As a workaround you can exclude it since it's just a sample:
implementation("com.github.kotlin-telegram-bot:kotlin-telegram-bot:6.0.4") {
exclude(module = "webhook")
}

Strange exception thrown in Ktor

Today i encountered a strange status page exception being thrown in Ktor.
I am trying to build a simple api with ktor and i did this Route:
fun Route.phrase(db : Repository){
post(PHRASE_ENDPOINT){
val request = call.receive<Request>()
val phrase = db.add(EmojiPhrase(request.toString(), request.toString()))
this.call.respond(phrase)
}}
when i try to send the request i get
java.lang.ClassNotFoundException: kotlinx.coroutines.io.ByteReadChannel
has anyone encountered this problem
im using :
ktor_version=1.3.2,
kotlin_version=1.4.10,
moshi_version= 1.0.1
Issue appears to be in moshi converter: https://github.com/rharter/ktor-moshi/issues/7#issuecomment-580977097
Until the PR is merged, you can use the patched version through
jitpack
buildscript {
repositories {
jcenter()
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.cs125-illinois:ktor-moshi:7252ca49ed'
}

How to Run Ktor Embedded Server from Code

I've written a simple Ktor server that processes a JSON payload from an incoming POST request. Now, I want to spawn this server from another application, and after processing the request, shut it down.
So the first problem I need to solve is: how do I spawn the Ktor server from some other 'driver' Kotlin code? All the tutorials I've found online are 1-2 years old, and are apparently using an older version of Ktor, where the main class looks like this:
fun main(args: Array<String>) {
embeddedServer(Netty, 8080) {
routing {
get("/") {
call.respondText("Hello from Kotlin Backend", ContentType.Text.Html)
}
}
}.start(wait = true)
}
It's easy to see that one can just run the embeddedServer(Netty, 8080) { ... }.start(wait = true) from wherever they want, to spawn the server. But I downloaded the Ktor plugin for IntelliJ IDEA yesterday, and it seems things have changed lately. This is what the new main class looks like:
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
#Suppress("unused") // Referenced in application.conf
#kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
gson {
}
}
routing {
get("/") {
call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}
get("/json/gson") {
call.respond(mapOf("hello" to "world"))
}
}
}
Now, the Application.module(...) function takes care of setting up the routing and stuff, while the actual running of the server is done internally by io.ktor.server.netty.EngineMain.main(args). Also, properties like the port number are referenced from the application.conf file, and I'm not quite sure how it figures out where to find that application.conf file.
I have been able to run this Ktor server using gradlew. I also understand that it is possible to export it as an executable jar and run it (as explained here). But I can't find out how to run it from code. Any suggestions?
Edit: And it would be nice if I could set the port number from the driver code.

Kotlin class servlet provoke NoClassDefFoundError

In a sample Java servlet project in my IntelliJ IDE, i have created this class in Kotlin :
#WebServlet(name = "TwitterAPIServlet", description = "This is used to test the servlet api", urlPatterns = ["/twitterAPIServlet"])
class TwitterAPIServlet : HttpServlet() {
#Throws(IOException::class)
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
// Print answer
val out = resp.writer
out.println("Request Done : </br>")
}
}
When i am trying to call this with my .jsp page, i have this error :
2020-05-10 15:30:34.218:WARN:oejs.HttpChannel:qtp60559178-27: /twitterAPIServlet
java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
at main.java.co.rezo.api.internal.v1.TwitterAPIServlet.doGet(TwitterAPIServlet.kt)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
When i am trying the same code in Java, it's working :
#WebServlet(
name = "TwitterAPIServlet",
description = "This is used to test the servlet api",
urlPatterns = "/twitterAPIServlet")
public class TwitterAPIServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
out.println("Request Done : </br>");
}
}
What can i do to make my Kotlin code working?
Most probably the issue is that Kotlin's standard library is not included in the generated WAR (or is not on a classpath if you run the exploded app). Make sure to include it in your build.
Instructions for Gradle can be found in the official examples repository: kotlin-examples.
Maven is similar: https://kotlinlang.org/docs/reference/using-maven.html.
In case of pure IDEA (though it's recommended to use one of the build tools above), check the projects settings:
You should see Kotlin's stdlib included in the artifact:

Quarkus Vert.x Example

I want to test Quarkus and the native image for Docker with an existing project written in Kotlin and using Vert.x verticles.
Can you point me to an example on how to deploy verticles using Quarkus?
My dependencies are vertx-sockjs-service-proxy and vertx-lang-kotlin.
I found some examples in the Vert.x extension tests but I cannot find how to deploy my verticles at server startup.
#Inject
EventBus eventBus;
#Route(path = "/hello-event-bus", methods = GET)
void helloEventBus (RoutingExchange exchange){
eventBus.send("hello", exchange.getParam("name").orElse("missing"), ar -> {
if (ar.succeeded()) {
exchange.ok(ar.result().body().toString());
} else {
exchange.serverError().end(ar.cause().getMessage());
}
});
}
You can use verticle as follows:
#Inject Vertx vertx;
void onStart(#Observes StartupEvent ev) {
vertx.deploy(new MyVerticleA());
vertx.deploy(new MyVerticleB());
}