How to share Java code between Android and JVM targets (with Kotlin Multiplatform)? - kotlin

I am trying to share Java code between Android and JVM targets using Kotlin Multiplatform feature (sample project: https://github.com/dmitrykolesnikovich/accessJavaCode-issue)
Simply saying, ":library1" and ":library2" both are Kotlin multiplatform libraries targeting JVM and Android. ":library2" depends on ":library1". They both uses Kotlin and Java. ":library2" is intended to be dependency of 1) Android application and 2) desktop (JavaFX) application. That's why 1) AAR artifact and 2) JAR artifact both are needed (?) - so I use 1) Android target and 2) JVM target for both ":library1" and ":library2".
The problem is that, when I have Java code in ":library1"
public class JavaCode {} // JavaCode.java
And Kotlin code in ":library2" that depends on ":library1"
class AccessJavaCode : JavaCode() // AccessJavaCode.kt
Android target is OK with recognizing Java but JVM target is not:
> Task :library2:compileKotlinJvm FAILED
e: AccessJavaCode.kt: (3, 38): Unresolved reference: JavaCode
In gradle config I define two plugins: kotlin-multiplatform and com.android.library:
apply plugin: "kotlin-multiplatform"
apply plugin: "com.android.library"
kotlin {
targets {
jvm()
android()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
}
}
androidMain {
dependsOn jvmMain
}
}
}
android {
compileSdkVersion 28
sourceSets {
main {
java.srcDirs += "src/jvmMain/kotlin" // Android target recognizes Java with this
manifest.srcFile "src/androidMain/AndroidManifest.xml"
}
}
}
I am pretty sure it’s something simple with my gradle file. Many thanks for your help guys.

~~~~ EDIT ~~~~
Another workaround the issue without losing the ability to generate an android archive .aar for the library1 would be to make a new version of this same library depending on precompiled artefacts of a splitted version of the original library1.
So you would end up with a multi-module gradle project, something like this:
library1-jvm with java plugin enabled
library1-android with android plugin enabled
library1 which will depends on prebuilt library1-jvm.jar and library1-android.aar
You could use whatever you prefer to publish those artefacts, but a local maven repo should work just fine!
That would mean replacing:
kotlin {
targets {
jvm()
android()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
}
}
androidMain {
dependsOn jvmMain
}
}
}
with:
kotlin {
targets {
jvm()
android()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
api "com.company:library-jvm:1.0.0"
}
}
androidMain {
dependsOn jvmMain
dependencies {
api "com.company:library-android:1.0.0"
}
}
}
}
That way, you don't need the java plugin at all in the final library1, because all the java code will already be built in a separate step.
Hence library1 could keep both the JVM and Android targets
~~~~~~~~~~~~~
In order to fix your issue, you need to:
Split your build.gradle configuration in order to have one config per library, this will be needed because you cannot enable the java plugin and the android at the same time for the same Gradle project, or you will end up with the following Error: The 'java' plugin has been applied, but it is not compatible with the Android plugins
Enable the java plugin in your library1 project if you want your JVM target to recognize your Java source files.
The Java source files need to be placed in the sibling directories java of the kotlin source roots.
More infos: Kotlin docs for java-support-in-jvm-targets
I also created a pull request solving your issue.
The downside of this approach is that you will not be able to generate an android archive .aar for the library1, but I guess using the java archive .jar in your android project should not be a problem at all.
library1/build.gradle:
apply plugin: "kotlin-multiplatform"
kotlin {
jvm {
withJava()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
}
}
}
}
library2/build.gradle:
apply plugin: "kotlin-multiplatform"
apply plugin: "com.android.library"
kotlin{
jvm()
android()
sourceSets {
jvmMain.dependencies {
api project(":library1")
}
androidMain {
dependsOn jvmMain
}
}
}
android {
compileSdkVersion 28
sourceSets {
main {
java.srcDirs += "src/jvmMain/kotlin"
manifest.srcFile "src/androidMain/AndroidManifest.xml"
}
}
}

Related

"Could not find method wrapper()" in build.gradle file generated by openapi-generator kotlin client

I have a simple spring boot project using the kotlin gradle dsl. I want to generate an OpenApi client using the openapi client generator gradle Plugin. I have successfully done so, using this configuration. Until now, this was a single project build. But when i try to include it, i get an error message "Could not find method wrapper()".
This is how i generated the client and added it's file into my source sets:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.0.2"
id("io.spring.dependency-management") version "1.1.0"
kotlin("jvm") version "1.7.22"
kotlin("plugin.spring") version "1.7.22"
id("org.openapi.generator") version "6.3.0"
}
// other dependencies
openApiGenerate {
generatorName.set("kotlin")
inputSpec.set("src/main/openapi/my-api.yml")
outputDir.set("$buildDir/generated/my-api")
packageName.set("com.myapi")
}
kotlin.sourceSets["main"].kotlin.srcDir("$buildDir/generated/my-api/src/main/kotlin")
Now i want to use this generated client in my project. It comes with it's own build.gradle (in groovy) which loads the necessary dependencies etc.
I have modified my settings.gradle.kts file accordingly:
rootProject.name = "myapp"
include("build:generated:my-api")
When i reload gradle, i get the follwing error:
> Could not find method wrapper() for arguments [build_gdswinwcvulw9afq79kj4v6h$_run_closure1#582f32f7] on project ':build:generated:my-api' of type org.gradle.api.Project.
This is due to the build.gradle file generated by the generator looking like this:
group 'org.openapitools'
version '1.0.0'
wrapper {
gradleVersion = '7.5'
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}
buildscript {
ext.kotlin_version = '1.7.21'
repositories {
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'maven-publish'
repositories {
maven { url "https://repo1.maven.org/maven2" }
}
test {
useJUnitPlatform()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
implementation "com.squareup.moshi:moshi-kotlin:1.13.0"
implementation "com.squareup.moshi:moshi-adapters:1.13.0"
implementation "com.squareup.okhttp3:okhttp:4.10.0"
testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2"
}
I am using Gradle 7.6 and i am a bit out of ideas here since i am pretty new to Gradle.

How to import a file from another directory in Kotlin?

I have a gradle kotlin project, and I'm generating a kotlin file from a Rust project, so it ends up in a totally different place with no gradle project structure, etc.
How do I import this file into my gradle project?
It has its own package but it's a completely standalone file. This is my gradle file:
rootProject.name = "my_project"
include("app")
It's a desktop project, NOT android.
My build.gradle.kts:
plugins {
// Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
id("org.jetbrains.kotlin.jvm") version "1.5.31"
// Apply the application plugin to add support for building a CLI application in Java.
application
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Align versions of all Kotlin components
implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
// Use the Kotlin JDK 8 standard library.
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
// This dependency is used by the application.
implementation("com.google.guava:guava:30.1.1-jre")
// Use the Kotlin test library.
testImplementation("org.jetbrains.kotlin:kotlin-test")
// Use the Kotlin JUnit integration.
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
application {
// Define the main class for the application.
mainClass.set("my_project.ffi.AppKt")
}
Adding the following code to your build.gradle.kts should do the trick (tested with Gradle 7.3.2):
// TODO: replace this dummy task with the task from your Rust project which
// generates the Kotlin source directory. Make sure that the generated
// directory (with the Kotlin file(s)) is the task output directory.
val rustTask by tasks.registering(Copy::class) {
// To test this, I had simply put a Kotlin file into this "somewhere"
// directory.
from("somewhere")
into(temporaryDir)
}
sourceSets {
main {
java {
srcDir(rustTask)
}
}
}
tasks {
compileKotlin {
dependsOn(rustTask)
}
}
So, we’re simply adding the generated sources as an additional source directory to the default SourceSet which is consumed by the compileKotlin task. In addition, we make sure that the sources are generated before compileKotlin runs.

Applying org.jetbrains.kotlin.jvm within custom Gradle plugin not working

I'm writing a custom Gradle plugin using Kotlin. The goal is to apply and configure certain plugins within this custom plugin. Consumers should only need to apply the custom plugin and be all set.
The problem:
I want to apply these two kotlin plugins (and other plugins) in the custom plugin (which can be applied like this normally in a Gradle build script):
kotlin("jvm") version "1.4.10"
kotlin("plugin.spring") version "1.4.10"
But when applying them from within my own plugin a couple of things goes wrong.
The jar task is not found. I get this complaint in the project consuming my plugin.
The contents of the dependencies section, e.g api, implementation etc are also causing errors, like if Gradle doesn't understand what they are.
I can, in the consuming project however, simply add the line below to the build script to get the jar task back, and make dependencies work again:
kotlin("jvm") version "1.4.10"
I also wrote a sort of debug function in the consuming Gradle build, just to see what plugins are applied. They all print true when I apply only my own plugin (or add kotlin-jvm to the script manually). Which seems to me like my own plugin is doing its job.
open class GreetingTask : DefaultTask() {
#TaskAction
fun greet() {
println("hello from GreetingTask")
println(project.pluginManager.hasPlugin("org.springframework.boot"))
println(project.pluginManager.hasPlugin("io.spring.dependency-management"))
println(project.pluginManager.hasPlugin("com.github.ben-manes.versions"))
println(project.pluginManager.hasPlugin("org.jetbrains.kotlin.jvm"))
println(project.pluginManager.hasPlugin("org.jetbrains.kotlin.plugin.spring"))
println(project.pluginManager.hasPlugin("java"))
}
}
My apply method so far in my plugin:
override fun apply(project: Project) {
configureRepositories(project)
configureTesting(project)
configureJava(project)
configureSpringBoot(project)
configureSpringDependencyManagement(project)
configureKotlin(project)
configureVersions(project)
configurePublishing(project)
}
And for setting up Kotlin:
private fun configureKotlin(project: Project) {
project.pluginManager.apply("org.jetbrains.kotlin.jvm")
project.pluginManager.apply("org.jetbrains.kotlin.plugin.spring")
project.tasks.withType(KotlinCompile::class.java).configureEach { task ->
task.kotlinOptions.freeCompilerArgs = listOf("-Xjsr305=strict")
task.kotlinOptions.jvmTarget = "11"
}
}
All the other configureXYZ seems to work out fine.
I solved it. The problem was how I applied the plugin.
This does NOT work:
build.gradle.kts
buildscript {
repositories {
mavenLocal()
gradlePluginPortal()
}
dependencies {
classpath("com.praqma:demo:1.0.0")
}
}
apply(plugin = "com.praqma.demo.DemoPlugin")
This does work:
settings.gradle.kts
pluginManagement {
repositories {
mavenLocal()
gradlePluginPortal()
}
}
build.gradle.kts
plugins {
id("gradle.demoPlugin") version "0.0.1-SNAPSHOT"
}

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 build kotlinx.coroutines in Kotlin/Native (test version 0.23.4-native-1)

This question is a continuation of this thread:
https://github.com/Kotlin/kotlinx.coroutines/issues/246#issuecomment-407023156
I am trying to use org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1 in a Kotlin/Native project targeting iOS.
build.gradle:
buildscript {
repositories {
mavenCentral()
maven { url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies" }
}
dependencies {
classpath 'org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.8'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}
}
apply plugin: 'kotlin-platform-native'
repositories {
jcenter()
mavenCentral()
maven { url "https://kotlin.bintray.com/kotlinx" }
}
sourceSets {
main {
component {
target 'ios_arm32', 'ios_arm64', 'ios_x64'
outputKinds = [KLIBRARY]
}
}
}
dependencies {
expectedBy project(':common')
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1"
}
The kotlinx:kotlinx-coroutines-core-native dependency doesn't seem to work, as the produces build errors like:
error: unresolved reference: coroutines
import kotlinx.coroutines.experimental.*
^
If I manually include the artifact dependencies such as org.jetbrains.kotlinx:kotlinx-coroutines-core-native_release_ios_x64:0.10.3-native, then I get a complier exception:
exception: java.lang.IllegalStateException: Could not find "atomicfu-native"
This error persists, even if I also add org.jetbrains.kotlinx:atomicfu-native:0.10.3-native dependency.
Here is a list of things to check for (I have been through this, and finally made it work) :
Enable Gradle metadata. It's required to retrieve the coroutines dependencies. To do so, add this line in your "settings.gradle" file, after all the "include" instructions :
enableFeaturePreview('GRADLE_METADATA')
use gradle 4.7 (newer version are incompatible with the meta data of the current coroutines library, they require something with 0.4 version and the current published one uses 0.3)
In the iOS module :
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1"
In your common module :
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.4"
If you have a js module, it may fail due to the gradle metadata feature. You can fix it by adding this before each of your "repositories" blocks (https://github.com/srs/gradle-node-plugin/issues/301)
repositories.whenObjectAdded {
if (it instanceof IvyArtifactRepository) {
metadataSources {
artifact()
}
}
}
Hope this will be enough !