Kotlin MPP - build problems with Gradle on IntelliJ - gradle

I'm trying to build a multi module Gradle project with some Koltin MPP modules.
I have a very strange problem while trying to build a Kotlin MPP module. All of the specified dependencies are resolved, they can be seen from the Gradle configuration, but when I try to use some of the classes in the mobile targets (Android and iOS), I can't do it. The classes can't be resolved at all.
This is my gradle build file for the module in question:
plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.multiplatform'
id 'org.jetbrains.kotlin.plugin.serialization'
}
group 'bg.dalexiev'
version '0.0.1'
def ktor_version = '1.3.1'
def serialization_version = '0.14.0'
def coroutines_version = '1.3.3'
def timber_version = '4.7.1'
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 21
versionName '0.0.1'
versionCode 1
}
sourceSets {
main {
manifest.srcFile 'src/androidMain/AndroidManifest.xml'
java.srcDirs = ['src/androidMain/kotlin']
res.srcDirs = ['src/androidMain/res']
}
test {
java.srcDirs = ['src/androidTest/kotlin']
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
repositories {
google()
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation "io.ktor:ktor-client-okhttp:$ktor_version"
implementation "io.ktor:ktor-client-json-jvm:$ktor_version"
implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"
implementation "io.ktor:ktor-client-logging-jvm:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "com.jakewharton.timber:timber:$timber_version"
testImplementation("junit:junit:4.12")
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
kotlin {
android("android")
def sdkName = System.getenv('SDK_NAME')
def iosTarget = sdkName?.startsWith('iphoneos') ? presets.iosArm64 : presets.iosX64
targetFromPreset(iosTarget, "ios") {
binaries {
framework()
}
}
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib-common')
implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-client-json:$ktor_version"
implementation "io.ktor:ktor-client-serialization:$ktor_version"
implementation "io.ktor:ktor-client-logging:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
}
}
iosMain {
dependencies {
implementation "io.ktor:ktor-client-ios:$ktor_version"
implementation "io.ktor:ktor-client-json-native:$ktor_version"
implementation "io.ktor:ktor-client-serialization-native:$ktor_version"
implementation "io.ktor:ktor-client-logging-native:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:$serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:$coroutines_version"
}
}
iosTest {
}
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
configurations {
compileClasspath
}
I was able to build a standalone gradle project with the same configuration without any problems. Any help and advice would be appreciated.

Your android dependencies are in the wrong block. Refactor your build.gradle to
plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.multiplatform'
id 'org.jetbrains.kotlin.plugin.serialization'
}
group 'bg.dalexiev'
version '0.0.1'
def ktor_version = '1.3.1'
def serialization_version = '0.14.0'
def coroutines_version = '1.3.3'
def timber_version = '4.7.1'
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 21
versionName '0.0.1'
versionCode 1
}
sourceSets {
main {
manifest.srcFile 'src/androidMain/AndroidManifest.xml'
java.srcDirs = ['src/androidMain/kotlin']
res.srcDirs = ['src/androidMain/res']
}
test {
java.srcDirs = ['src/androidTest/kotlin']
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
repositories {
google()
}
kotlin {
android("android")
def sdkName = System.getenv('SDK_NAME')
def iosTarget = sdkName?.startsWith('iphoneos') ? presets.iosArm64 : presets.iosX64
targetFromPreset(iosTarget, "ios") {
binaries {
framework()
}
}
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib-common')
implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-client-json:$ktor_version"
implementation "io.ktor:ktor-client-serialization:$ktor_version"
implementation "io.ktor:ktor-client-logging:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
}
}
androidMain.dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation "io.ktor:ktor-client-okhttp:$ktor_version"
implementation "io.ktor:ktor-client-json-jvm:$ktor_version"
implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"
implementation "io.ktor:ktor-client-logging-jvm:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "com.jakewharton.timber:timber:$timber_version"
}
androidTest.dependencies {
implementation("junit:junit:4.12")
implementation("org.jetbrains.kotlin:kotlin-test")
implementation("org.jetbrains.kotlin:kotlin-test-junit")
}
iosMain {
dependencies {
implementation "io.ktor:ktor-client-ios:$ktor_version"
implementation "io.ktor:ktor-client-json-native:$ktor_version"
implementation "io.ktor:ktor-client-serialization-native:$ktor_version"
implementation "io.ktor:ktor-client-logging-native:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:$serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:$coroutines_version"
}
}
iosTest {
}
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
configurations {
compileClasspath
}

Related

Deploy in railway not working with gradle.build.kt

I need to deploy a aplication in railway, but any time returno this error:
Caused by: java.lang.ClassNotFoundException: br.com.zezinho.helpdesk
Error: Could not find or load main class br.com.zezinho.helpdesk
My path is correct.
github: https://github.com/Luciannodev/helpdesk-back
plugins {
java
id("org.springframework.boot") version "2.7.8"
id("io.spring.dependency-management") version "1.1.0"
}
group = "br.com.zezinho"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
val mainClassName = "HelpDeskApplication.java"
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
repositories {
mavenCentral()
maven { url = uri("https://repo.spring.io/milestone") }
maven { url = uri("https://repo.spring.io/snapshot") }
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("io.jsonwebtoken:jjwt-api:0.11.5")
implementation("io.jsonwebtoken:jjwt-impl:0.11.5")
implementation("io.jsonwebtoken:jjwt-jackson:0.11.5")
implementation("mysql:mysql-connector-java:8.0.28")
implementation("com.h2database:h2:1.4.200")
testImplementation("org.springframework.boot:spring-boot-starter-test")
annotationProcessor("org.projectlombok:lombok")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.jar {
manifest.attributes["Main-Class"] = "br.com.zezinho.helpdesk"
manifest.attributes["Class-Path"] = configurations
.runtimeClasspath
.get()
.joinToString(separator = " ") { file ->
"libs/${file.name}"
}
}

No compileOnly configuration in the build.gradle but it is

I have the following error message during the build, but no compileOnly dependency in my build.gradle. Why it's happens, and how to solve?
Regards
Resolving dependency configuration 'compileOnly' is not allowed as it
is defined as 'canBeResolved=false'. Instead, a resolvable
('canBeResolved=true') dependency configuration that extends
'compileOnly' should be resolved.
buildscript {
ext.kotlin_version = '1.6.0'
repositories {
mavenCentral()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots/"
}
maven {
url "https://plugins.gradle.org/m2/"
}
repositories {
flatDir {
dirs 'jars'
}
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
plugins {
id "org.jetbrains.intellij" version "1.10.1"
id "org.jetbrains.grammarkit" version "2020.1"
}
configurations {
configurations.implementation.setCanBeResolved(true)
}
group 'com.interfaced'
version '0.2.7'
apply plugin: 'kotlin'
apply plugin: 'org.jetbrains.intellij'
sourceSets {
all {
java.srcDirs += ['src/main/gen']
kotlin.srcDirs += ['src/main/kotlin']
resources.srcDirs = ['src/main/resources']
}
}
grammarKit {
jflexRelease = '1.7.0-2'
}
repositories {
mavenCentral()
maven {
url "https://cache-redirector.jetbrains.com/intellij-dependencies"
}
}
dependencies {
// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib
compileClasspath group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: '1.7.22'
compileClasspath files('jars/grammar-kit.jar')
compileClasspath group: 'junit', name: 'junit', version: '4.12'
compileClasspath "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
}
intellij {
version '2022.3'
}
import org.jetbrains.grammarkit.tasks.GenerateLexer
import org.jetbrains.grammarkit.tasks.GenerateParser
def GENERATE_GROUP = 'Generate'
task generateLexer(type: GenerateLexer) {
source = "src/main/grammar/BrightScript.flex"
targetDir = "src/main/gen/com/interfaced/brs/lang/lexer"
targetClass = "_BrsLexer"
skeleton = "src/main/grammar/idea-flex.skeleton"
purgeOldFiles = true
description = 'Generate Lexer Java sources for BrightScript'
group = GENERATE_GROUP
}
task generateParser(type: GenerateParser) {
source = "src/main/grammar/BrightScript.bnf"
targetRoot = 'src/main/gen'
pathToParser = 'src/main/gen/com/interfaced/brs/lang/BrsParser.java'
pathToPsiRoot = 'src/main/gen/com/interfaced/brs/lang/psi'
purgeOldFiles = true
description = 'Generate Parser Java sources for BrightScript'
group = GENERATE_GROUP
// patch up to date check
outputs.upToDateWhen { false }
}
compileKotlin {
kotlinOptions.jvmTarget = "17"
}
compileKotlin.dependsOn(generateLexer, generateParser)

Getting error while running spot bugs "A failure occurred while executing com.github.spotbugs.snom.internal.SpotBugsRunnerForWorker$SpotBugsExecutor"

Getting error while running spot bugs "A failure occurred while executing com.github.spotbugs.snom.internal.SpotBugsRunnerForWorker$SpotBugsExecutor"
Gradle Version :- 6.6.1
SpotBug plugin- 4.2
plugins {
id 'java'
id 'io.quarkus'
id "com.github.spotbugs" version "4.2.0"
}
repositories {
mavenCentral()
}
sourceSets {
main {
java {
srcDir 'src/main/java'
}
resources {
srcDir 'src/main/resources'
}
}
}
dependencies {
compile "org.apache.commons:commons-lang3:3.11"
compile "org.jboss.logmanager:log4j2-jboss-logmanager"
compile 'org.jboss.slf4j:slf4j-jboss-logging'
compile 'org.jboss.logging:commons-logging-jboss-logging'
spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.10.1'
}
compileJava {
options.encoding = 'UTF-8'
options.compilerArgs << '-parameters'
}
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
spotbugs {
toolVersion = '4.2.0'
}

Import of external class in Kotlin Gradle Script not found

In my build.gradle.kts, I want to write a function that uses an external class: StrSubstitutor from Apach Commons Text. However, the import is not found, although I can see the library when I run ./gradlew dependencies.
The build.gradle.kts file is as follows:
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.apache.commons.text.StringSubstitutor // Import not found
plugins {
val kotlinVersion = "1.3.61"
kotlin("jvm") version "$kotlinVersion"
kotlin("kapt") version "$kotlinVersion"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.apache.commons:commons-text:1.8")
// SourceSets
sourceSets.main {
withConvention(KotlinSourceSet::class) {
kotlin.srcDirs("src/main/kotlin")
}
}
sourceSets.test {
withConvention(KotlinSourceSet::class) {
kotlin.srcDirs("src/main/kotlin")
}
}
}
tasks.withType<Test> {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
systemProperty("spring.profiles.active", "test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
// Function that uses the import
fun getProperty(properties: Properties, propertyKey: String): String {
// Use the import "StrSubstitutor"
return ""
}
Is this possible with Kotlin, and if so: how?
Yes, it is possible. The reason it does not work as written is because you put the dependency on the Apache Commons Text into implementation configuration of the project, not into the classpath of the build script itself. So, you basically need to introduce a buildscript block to your build.gradle.kts file. Below is an example1:
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.apache.commons.text.StringSubstitutor
// TL DR: Add this block to your build script to make the import above work
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.apache.commons:commons-text:1.8")
}
}
tasks.register("hello") {
doLast {
println(StringSubstitutor.replaceSystemProperties(
"You are running with Java \${java.version} on OS \${os.name}."))
}
}
plugins {
val kotlinVersion = "1.3.61"
kotlin("jvm") version "$kotlinVersion"
kotlin("kapt") version "$kotlinVersion"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
// You probably do not need this for your project, so I commented it out
// implementation("org.apache.commons:commons-text:1.8")
// SourceSets
sourceSets.main {
withConvention(KotlinSourceSet::class) {
kotlin.srcDirs("src/main/kotlin")
}
}
sourceSets.test {
withConvention(KotlinSourceSet::class) {
kotlin.srcDirs("src/main/kotlin")
}
}
}
tasks.withType<Test> {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
systemProperty("spring.profiles.active", "test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
Run this script with ./gradlew -q hello to check whether it works or not.
1 New task hello exists there just to demonstrate that the import works, it is not needed in the final build script that you would use in your project.

Gradle can't resolve references from another module

I have a project with the following modules:
App
Device
App depends on device. Device contains a NetworkComponent class that app references. More specifically:
package com.some.package.ui.login;
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.some.package.R
import com.some.package.device.network.NetworkComponent
import com.some.package.ui.terms.TermsActivity
class LoginActivity : AppCompatActivity(),
LoginViewModel.Navigator {
val loginViewModel by lazy { LoginViewModel(this, NetworkComponent()) }
Everything resolves fine in Android Studio. Yet when I attempt to build the project, I encounter a build error:
e: /Users/android/some-app-android/app/src/main/kotlin/com/some/package/ui/login/LoginActivity.kt: (7, 27): Unresolved reference: network
e: /Users/android/some-app-android/app/src/main/kotlin/com/some/package/ui/login/LoginActivity.kt: (13, 55): Unresolved reference: NetworkComponent
[KOTLIN] deleting /Users/android/some-app-android/app/build/tmp/kotlin-classes/debug on error
[KOTLIN] deleting /Users/android/some-app-android/app/build/tmp/kotlin-classes/debug on error
:app:compileDebugKotlin FAILED
This is what NetworkComponent looks like:
package com.some.package.device.network
import com.some.package.domain.datasources.CodeValidator
import retrofit2.Retrofit
class NetworkComponent : CodeValidator {
val codeValidator: CodeValidatorApi
init {
val retrofit = Retrofit.Builder()
.baseUrl("www.test.com")
.build()
codeValidator = retrofit.create(CodeValidatorApi::class.java)
}
override fun validate(code: String) = codeValidator.validate(code)
}
Here are the build files:
Top:
buildscript {
ext.kotlin_version = '1.1.51'
ext.android_tools = '3.0.0'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$android_tools"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
App:
buildscript {
repositories {
mavenCentral()
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
//apply plugin: 'io.fabric'
// Manifest version information
def versionMajor = 0
def versionMinor = 0
def versionPatch = 1
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.some.package"
minSdkVersion 21
targetSdkVersion 27
versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
// applicationIdSuffix '.debug'
resValue "string", "application_name", "TEST APP Debug"
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
resValue "string", "application_name", "TEST APP"
}
}
dataBinding {
enabled = true
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
debug.java.srcDirs += 'src/debug/kotlin'
}
packagingOptions {
exclude 'META-INF/ASL2.0'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/services/javax.annotation.processing.Processor' // butterknife
}
}
repositories {
maven { url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo' }
}
dependencies {
implementation project(':device')
implementation project(':data')
implementation project(':domain')
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:support-v4:27.0.0'
implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'com.android.support:design:27.0.0'
implementation 'com.android.support:support-annotations:27.0.0'
kapt "com.android.databinding:compiler:$android_tools"
// Logging
implementation 'com.jakewharton.timber:timber:4.5.1'
// Unit tests
testImplementation 'junit:junit:4.12'
// testImplementation 'org.robolectric:robolectric:3.0'
testImplementation 'org.mockito:mockito-core:2.11.0'
// testImplementation 'joda-time:joda-time:2.9.4'
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.1'
// releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
// testImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'
debugImplementation 'com.facebook.stetho:stetho:1.4.1'
debugImplementation 'com.uphyca:stetho_realm:2.0.0'
// implementation('com.crashlytics.sdk.android:crashlytics:2.6.8#aar') {
// transitive = true;
// }
}
Device:
apply plugin: 'com.android.library'
android {
compileSdkVersion 27
defaultConfig {
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':domain')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'
implementation "com.squareup.retrofit2:retrofit:2.3.0"
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
testImplementation 'junit:junit:4.12'
}
I'm not quite sure how this can happen. I tried downgrading the gradle plugin to 2.3.3, but no luck.
Any ideas?
Turns out I was missing this key line in my device module build file:
apply plugin: 'kotlin-android'
Thanks to this answer for the clue https://stackoverflow.com/a/31671696/918585

Resources