Micronaut #SerdeImport annotation not working with Kotlin - kotlin

I am working on developing an application using Micronaut framework with Kotlin language.
However, I am facing an issue where #SerdeImport annotation is not being recognized when using Micronaut with Kotlin.
I am getting the below error even after using the #SerdeImport annotation.
No serializable introspection present for type MarketSnapshot B.
Consider adding Serdeable. Serializable annotate to type MarketSnapshot B.
Alternatively if you are not in control of the project's source code,
you can use #SerdeImport(MarketSnapshot.class) to enable serialization of this type."}]}}
The same annotation works fine when using Java, however, it fails with the Kotlin program.
Below are the micronaut kotlin related dependencies that are used in build.gradle file
annotationProcessor 'io.micronaut:micronaut-inject-java'
annotationProcessor 'io.micronaut:micronaut-http-validation'
annotationProcessor 'io.micronaut.openapi:micronaut-openapi'
annotationProcessor 'io.micronaut.serde:micronaut-serde-processor'
kapt 'io.micronaut:micronaut-http-validation'
kapt 'io.micronaut:micronaut-inject-java'
implementation 'org.jetbrains.kotlin:kotlin-reflect:${kotlin}'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlin}'
implementation 'io.micronaut.kotlin:micronaut-kotlin-runtime'
implementation 'io.micronaut.serde:micronaut-serde-jackson'
implementation 'io.micronaut:micronaut-management'
implementation 'io.micronaut:micronaut-http-client'
implementation 'io.micronaut:micronaut-jackson-databind'
implementation 'io.micronaut:micronaut-validation'
implementation 'jakarta.annotation:jakarta.annotation-api'

Do you have something like this in your build.gradle:
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(module("io.micronaut:micronaut-jackson-databind"))
.using(module("io.micronaut.serde:micronaut-serde-jackson:1.5.0"))
}
}
Also, think annotationProcessor 'io.micronaut.serde:micronaut-serde-processor' should be kapt("io.micronaut.serde:micronaut-serde-processor")
Micronaut Launch has a diff view to show the changes when adding a new feature.
For example: Micronaut Kotlin with serialization-jackson diff shows this for the changes to the build file:
dependencies {
kapt("io.micronaut:micronaut-http-validation")
+ kapt("io.micronaut.serde:micronaut-serde-processor")
implementation("io.micronaut:micronaut-http-client")
- implementation("io.micronaut:micronaut-jackson-databind")
implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
+ implementation("io.micronaut.serde:micronaut-serde-jackson")
implementation("jakarta.annotation:jakarta.annotation-api")
implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
## -57,3 +58,12 ##
annotations("com.example.*")
}
}
+
+
+
+configurations.all {
+ resolutionStrategy.dependencySubstitution {
+ substitute(module("io.micronaut:micronaut-jackson-databind"))
+ .using(module("io.micronaut.serde:micronaut-serde-jackson:1.5.0"))
+ }
+}

Related

Kotlin serialization plugin does not generate serializers in Gradle project

I'm trying to use the Kotlinx Serialization libraries and the associated Gradle plugin. It's supposed to generate serializers for when when I annotate a class with #Serializable, like this:
#Serializable
data class Message(val version: String)
// (...)
Json.encodeToString(Message("1.0"))
It does not work, and the annotation is highlighted with:
kotlinx.serialization compiler plugin is not applied to the module, so
this annotation would not be processed. Make sure that you've setup
your buildscript correctly and re-import project.
As expected, the code does not compile as I'm expecting to use the Serializers further down the line, with the error:
Type mismatch: inferred type is Message but
SerializationStrategy<TypeVariable(T)> was expected
Here is my app-level build.gradle:
plugins {
id "java"
id 'org.jetbrains.kotlin.jvm' version '1.6.10'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.6.10'
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(11))
}
}
dependencies {
implementation "com.amazonaws:aws-lambda-java-core:$lambda_runtime_version"
implementation "software.amazon.awssdk:dynamodb-enhanced:$aws_sdk_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlin_serialization_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
task fatJar(type: Jar) {
archiveClassifier = 'lambdaCode'
duplicatesStrategy = DuplicatesStrategy.WARN
from sourceSets.main.output
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.findAll { it.name.endsWith('jar') }.collect { zipTree(it) }
}
}
I'm using Gradle 7.3.3, and see all this in IntelliJ. I tried launching gradle build from the command line, with similar results, so the IDE does not seem to blame.
I read a lot of similar questions but I could not find an answer that worked for me. Can anyone shed some light on my situation?

Generate kotlin classes from xsd

There is an xsd schema. It is necessary to generate Kotlin-classes according to the xsd description. How can I do this? Using the code below, I can get java classes. But I need kotlin classes
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.3.21'
// Apply the application plugin to add support for building a CLI application.
id 'application'
/* Generate Java code from XSD */
id 'org.unbroken-dome.xjc' version '1.4.3'
}
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
xjc {
includeInMainCompilation = false
}
xjcGenerate {
source = fileTree('src/main/schema') { include '*.xsd' }
bindingFiles = fileTree('src/main/jaxb') { include '*.xjb' }
catalogs = fileTree('src/main/catalog') { include '*.cat' }
}
sourceSets {
main { java { srcDir xjcGenerate.outputDirectory } }
}
compileKotlin {
dependsOn xjcGenerate
}
/* END: Make xjcGenerate work with Kotlin */
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
mavenCentral()
google()
}
dependencies {
/* Add JAXB dependencies for Java 11 */
implementation 'javax.xml.bind:jaxb-api:2.3.1'
// Use the Kotlin JDK 8 standard library.
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
// Use the Kotlin test library.
testImplementation 'org.jetbrains.kotlin:kotlin-test'
// Use the Kotlin JUnit integration.
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
// Define the main class for the application.
mainClassName = 'ru.goryacms.AppKt'
I've tried https://github.com/reaster/schema-gen. It generates Kotlin data classes with annotations, but it has bugs so that the generated code does not compile, however this is easy to fix. In my case I also had to fix many annotations and some property names. Still much better than manually writing code.
You can try https://github.com/SixRQ/KAXB - Kotlin based class generator to generate native Kotlin classes from an XML Schema:
This project is used to generate native Kotlin classes from an xsd schema, similar to the JAXB tool for Java. The project will include a plugin for gradle and Intellij IDEA. ...
Once the archive has been extracted run the
bin/kaxb --P <destination package> --S <schema file> --T <target directory>

Trying to include swagger-codegen with gradle kotlindsl

I'm trying to make swagger codegen work in a project built with gradle (kotlin).
My reference is this example here : https://github.com/int128/gradle-swagger-generator-plugin which is made in Gradle groovy version.
Now the build.gradle.kts is the following:
repositories {
jcenter()
}
plugins {
java
id("org.springframework.boot") version "2.1.2.RELEASE"
id("io.spring.dependency-management") version "1.0.6.RELEASE"
id("org.hidetake.swagger.generator") version "2.16.0"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation ("io.swagger:swagger-annotations:1.5.21")
swaggerCodeGen("io.swagger:swagger-codegen-cli:2.3.1")
// Use JUnit test framework
testImplementation ("junit:junit:4.12")
}
swaggerSources {
petstore {
inputFile = file('petstore.yaml')
code {
language = 'spring'
}
}
}
But IntelliJ does not like lines talking about swagger:
I am a newbie in gradle so I don't understand what I am supposed to do. Is swaggerCodeGen supposed to be a function? Where does this function supposed to be imported? Where swaggerSources supposed to imported?
import org.hidetake.gradle.swagger.generator.GenerateSwaggerCode
// plugins, repositories are same, but note import above ^^^
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation ("io.swagger:swagger-annotations:1.5.21")
"swaggerCodegen"("io.swagger:swagger-codegen-cli:2.3.1") // 1
// Use JUnit test framework
testImplementation ("junit:junit:4.12")
}
swaggerSources {
create("petstore").apply { // 2
setInputFile(file("petstore.yaml")) // 3
code(closureOf<GenerateSwaggerCode> { // 4
language = "spring"
})
}
}
1 - dynamically resolved configuration in Kotlin looks like this (dynamically from Groovy, so there is problematically to use it on compile time, extension invoke operator on String is our saviour);
2 - swaggerSources returns you NamedDomainObjectContainer<SwaggerSource>, so to add new container we invoke create with it's name as parameter;
3 - Kotlin does not as flexible as Groovy, so calling setter instead of setting field;
4 - Groovy's closure is far from functional interface, so we specify generic type as in plugin's sources Closure is not parametrised.
You can use this openapi-generator plugin task to generate the swagger code as well.
It does the same thing as the swagger codegen plugin. Use it in your build.gradle.kts like:
plugins {
id("org.openapi.generator") version "5.1.1"
}
openApiGenerate {
generatorName.set("spring")
inputSpec.set("$rootDir/src/main/resources/petstore.yaml")
outputDir.set("$buildDir/generated/")
}
dependencies {
//Spring boot dependency
implementation("org.springframework.boot:spring-boot-starter-web")
// For swagger generated code and annotations
implementation("io.springfox:springfox-boot-starter:3.0.0")
implementation("javax.validation:validation-api:2.0.0.Final")
}
This could be used with a kotlin or java project, then you need to add the generated classes to your sourceSet by doing:
configure<SourceSetContainer> {
named("main") {
java.srcDir("$buildDir/generated/src/main/java")
}
}
The last step is make sure you generate the swagger files before compiling, for Kotlin, add this in your compile task:
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
dependsOn("openApiGenerate")
kotlinOptions.jvmTarget = "11"
}
You can check the generator's properties to adjust the configuration of the generated files.

Dagger and Kotlin. Dagger doesn't generate component classes

I'm new with kotlin and Dagger. I have a little problem that I do not how to solve and I don't find a solution.
So this is what I have:
#Module
class AppModule (app: Application) {
private var application: Application;
init {
this.application = app;
}
#Provides fun provideApplication(): Application? {
return application;
}
#Provides fun provideResources(): Resources? {
return application.resources;
}
}
#Singleton
#Component(modules = arrayOf(AppModule::class))
interface AppComponent: AppComponentBase {
public class Initializer {
private constructor(){}
companion object {
fun Init(app: Application): AppComponent? {
return DaggerAppComponent.builder().appModule(AppModule(app)).build()
}
}
}
}
AppComponentBase: This interface contain all the methods needed by this component.
Now, the problem is that this DaggerAppComponent class is not generated by Dagger if I do this DaggerAppComponent.builder().appModule(AppModule(app)).build() invocation within the companion object.
If a invoke the same line any were by the companion object dagger generate de class without any problem.
An other thing I did look for a solution was create an other different class with the same structure, and importe the DaggerAppComponent as internal object, and I the same result happened.
I don't what to have the initialization of the component outside. So, there any other alternative solution, or what am I doing wrong?.
You need to have the kapt processor in build.gradle:
kapt {
generateStubs = true
}
dependencies {
...
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'com.google.dagger:dagger:2.0.2'
kapt 'com.google.dagger:dagger-compiler:2.0.2'
...
}
This extension will generate the code for dagger.
Additionally, for newer gradle versions, you can also apply the plugin in your build.gradle:
apply plugin: 'kotlin-kapt'
dependencies {
...
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'com.google.dagger:dagger:2.0.2'
kapt 'com.google.dagger:dagger-compiler:2.0.2'
...
}
You can check this project for reference
I don't know when this change happened, but on 1.1.2 of the Kotlin gradle plugin you replace this (in your module's build.gradle):
kapt {
generateStubs = true
}
with this:
apply plugin: 'kotlin-kapt'
and then make sure to replace dependencies that use annotationProcessor with kapt.
For example, the old way would be to use:
annotationProcessor (
'some.library:one:1.0'
...
'some.library.n:n.0'
)
and now you use:
kapt (
'some.library:one:1.0'
...
'some.library.n:n.0'
)
UPDATE FOR KOTLIN 1.1.4
generateStubs does not work anymore. Feel free to make a build with the latest Kotlin and it would tell you in the Messages section of Android Studio that it is not necessary anymore. Here's an up-to-date list of dependencies for Dagger2 for Android and Kotlin
apply plugin: 'kotlin-kapt'
//...
// Other Gradle stuff
//...
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.1.4-3"
compile 'com.google.dagger:dagger-android:2.12'
kapt 'com.google.dagger:dagger-android-processor:2.12'
compileOnly 'com.google.dagger:dagger:2.12'
kapt 'com.google.dagger:dagger-compiler:2.12'
}
This issue can be fixed with the bellow change which is different from original answer
Following will also work well to fix this issue
with plugins
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
and dependencies
implementation "com.google.dagger:dagger:$dagger_version"
implementation "com.google.dagger:dagger-android:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
For reference check out this Gist
Use these dependencies if you are using kotlin as the primary language for android application development
// Dagger dependencies
def dagger_version = "2.44"
implementation "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
implementation "com.google.dagger:dagger-android:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version" // if you use the support libraries
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
My case must be some exclusion rule in Dagger's implementation
com.mycompany.native -> Dagger doesn't generate code
com.mycompany.other -> Dagger generates code
I wasted quite some time on this :-( I hope it helps someone else!
Sorry, I didn’t create a new issue, but decided to answer under similar questions, because maybe someone find it useful!
I faced to ridiculous issue! «Make Project» do not generate dagger files. They are generated while preparing run your App! But I was trying to solve problem for hours and didn't think of simple trying to click Run..)))
So, maybe you faced to the same problem:
Neither «Sync Project with Gradle» nor «Clean» and «Build Project» help generate dagger files.
-> Then just Run your App!
After the first Run App my Dagger started generated files if I click Make Project.
If u have problem withe DaggerComponent, You should add
apply plugin: 'kotlin-kapt'
kapt {
generateStubs = true
}
to build.gradleit will generate kotlin code for dagger 2 otherwise project will only build on Rebuild

Kotlin Foo::class.java "Unresolved Reference: Java" error

I am trying to convert my Java code of HomePage.class to Kotlin. I am following the instructions on Kotlin.org:
getClass()
To retrieve the type information from an object, we use the javaClass
extension property.
val fooClass = foo.javaClass
Instead of Java’s Foo.class use
Foo::class.java.
val fooClass = Foo::class.java
I have a class called HomePage that extends AppCompatActivity (in Android). I am using Android Studio. I tried doing HomePage::class.java and it has an error: Unresolved reference: java
How do I get this to work?
The issue is most likely that you forgot to depend on the reflection libraries which were needed for the reflective functions of Kotlin.
On the Java platform, the runtime component required for using the
reflection features is distributed as a separate JAR file
(kotlin-reflect.jar). This is done to reduce the required size of the
runtime library for applications that do not use reflection features.
If you do use reflection, please make sure that the .jar file is added
to the classpath of your project.
Source
It turns out, I was using an older version of Kotlin, and it wasn't configured correctly. I edited the gradle file to include the latest beta version, and selected the option that configures Kotlin, and it works now.
In gradle:
buildscript {
ext.kotlin_version = '1.0.0-beta-3594'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
I Put in the beginning of Gradle (Module app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
and
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
or
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
in the dependencies section
In the build.gradle (Project)
buildscript {
ext.kotlin_version = '1.2.0'
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
For easy reference, here are the reflection dependencies when using Gradle:
Reflection libraries from the docs for Gradle in your build.gradle
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
compile "org.jetbrains.kotlin:kotlin-reflect"
testCompile "org.jetbrains.kotlin:kotlin-test"
testCompile "org.jetbrains.kotlin:kotlin-test-junit"
}
Reflection libraries syntax for Kotlin Script Gradle DSL in your build.gradle.kts
dependencies {
compile(kotlin("stdlib"))
compile(kotlin("reflect"))
compile(kotlin("test"))
compile(kotlin("test-junit"))
}
In build.gradle (app) I had:
implementation 'androidx.core:core-ktx:1.6.0'
And I replaced it by
implementation 'androidx.core:core-ktx:1.5.0'
And it worked!
The core version also killed some of y functions like: forEach
I used
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
Instead of
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
i use this
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
invalided cache & restart android studio!works fine!!
This happened to me after updating Android Studio and the Kotlin plugin, which required migration to a newer version of Kotlin. After configuring everything correctly, the error still persisted. Deleting .idea folder and reloading did not help, but good old File -> Invalidate Caches / Restart did the trick for me.
I copied the class from other project and forgot to change the class package name.
when I changed, it fixed
I saw this in AndroidStudio with Kotlin 1.2.71 and none of the above fixed it for me.
What sadly hilariously worked for me was closing the project, telling AndroidStudio to forget about the project and re-opening from the folder. Presto, no unresolved reference. Weird, I know.
In my case reducing version of kotlin fixed the issue
Change
ext.kotlin_version = '1.3.21'
To
ext.kotlin_version = '1.3.11'
Add this line in your Module build gradle
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
In Project build gradle:
buildscript {
ext.kotlin_version = '1.3.21'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
I encountered this error when i downloaded and run android studio canary(artic fox). Since then my android studio(normal one) was giving this error i applied all the solutions given above but nothing worked . So i completely uninstalled the android studio and reinstalled the latest one (this was the only option left)