I want to use the Apache Lucence library to remove stopwords in my Android app and in my viewmodel's removeStopWords() function, I want to remove the stopwords from the given text. However, during the execution of the function, it gives the following "NoClassDefFoundError" error:
java.lang.NoClassDefFoundError: Failed resolution of:
Ljava/lang/ClassValue; at
org.apache.lucene.analysis.standard.StandardAnalyzer.createComponents(StandardAnalyzer.java:82)
at org.apache.lucene.analysis.Analyzer.tokenStream(Analyzer.java:199)
at
com.example.aidrawing.ui.homescreen.HomeViewModel.removeStopWords(HomeViewModel.kt:96)
...
My ViewModel:
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.aidrawing.data.models.TweetEntry
import com.example.aidrawing.repository.TweetRepository
import com.example.aidrawing.util.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.apache.lucene.analysis.TokenStream
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute
import javax.inject.Inject
#RequiresApi(Build.VERSION_CODES.N)
#HiltViewModel
class HomeViewModel #Inject constructor(
private val repository: TweetRepository
) : ViewModel() {
...
fun getTweets(username: String, count: Int) {
searchJob?.cancel()
searchJob = viewModelScope.launch {
repository.getAllTweets(username, count).onEach { result ->
when (result) {
is Resource.Loading -> {
Log.d("Mesaj: ", "Yükleniyor...")
}
is Resource.Success -> {
tweetList.clear()
for(i in result.data?.indices!!) {
tweetList.addAll(result.data[i].data.map { it.dataToTweetEntry() })
}
val text = tweetList.joinToString(separator = "") { it.text }
val textWithoutStopWords = removeStopWords(text)
val frequentWords = getMostFrequentWords(textWithoutStopWords, 10)
for ((word, frequency) in frequentWords) {
Log.d("Most frequent words", "$word: $frequency")
}
Log.d("Mesaj: ", "Son tivitin sonları: ${text.takeLast(40)}")
Log.d("Mesaj: ", "Son tivit: " + tweetList[tweetList.size-1].text)
Log.d("Mesaj: ", text)
Log.d("Mesaj: ", tweetList.size.toString())
}
is Resource.Error -> {
Log.d("Mesaj: ", result.message.toString())
}
}
}.launchIn(this)
}
}
...
fun removeStopWords(text: String): String {
val analyzer = StandardAnalyzer()
val tokenStream: TokenStream = analyzer.tokenStream("dummy", text)
val term = tokenStream.addAttribute(CharTermAttribute::class.java)
tokenStream.reset()
val filteredText = StringBuilder()
while (tokenStream.incrementToken()) {
filteredText.append(term.toString() + " ")
}
tokenStream.end()
tokenStream.close()
return filteredText.toString()
}
}
My build.gradle:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
id 'kotlin-parcelize'
}
android {
compileSdk 32
defaultConfig {
applicationId
"com.example.aidrawing"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion '1.5.21'
}
packagingOptions {
resources.excludes.add("META-INF/*")
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
...
//Apache Lucence
implementation 'org.apache.lucene:lucene-core:8.9.0'
}
How can I solve this problem? Thank you in advance for your help.
Related
I am discovering the new plugins declaration in Gradle. First applying below in the root Gradle file
plugins {
id("com.android.application") version "7.2" apply false
id("com.android.library") version "7.2" apply false
}
instead of
classpath 'com.android.tools.build:gradle:7.2.0'
And I also need the Gradle plugin in buildSrc so I have below in there, too
plugins {
`kotlin-dsl`
}
gradlePlugin {
plugins {
register("LibraryCommonPlugin") {
id = "libraryCommonPlugin"
implementationClass = "LibraryCommonPlugin"
}
}
}
repositories {
mavenCentral()
gradlePluginPortal()
google()
}
dependencies {
compileOnly(libs.plugin.android)
compileOnly(libs.plugin.kotlin)
implementation(libs.plugin.gradleVersions)
implementation(libs.kotlin)
compileOnly(gradleApi())
compileOnly(localGroovy())
}
And I have a common Gradle file that applies the plugin in child modules if is used
android_defaults.gradle
apply from: "$rootDir/buildsystem/helper.gradle"
apply plugin: "libraryCommonPlugin"
android {
defaultConfig {
...
app/build.gradle.kts
plugins {
id("com.android.application")
kotlin("android")
kotlin("kapt")
}
apply(from = "../buildsystem/android_defaults.gradle")
but then IDE throws an exception when I try to build
What went wrong: A problem occurred evaluating script.
com/android/build/gradle/AppPlugin
Caused by: java.lang.NoClassDefFoundError:
com/android/build/gradle/AppPlugin
Problems occuring from this custom plugin
class LibraryCommonPlugin : Plugin<Project> {
override fun apply(target: Project) {
target.plugins.all { plugin ->
when (plugin) {
is AppPlugin -> target.configureAndroid()
is LibraryPlugin -> target.configureLibrary()
is KotlinBasePluginWrapper -> target.configureWithKotlinPlugin()
}
true
}
}
private fun Project.configureAndroid() {
androidDependencies()
baseKotlinModuleDependencies()
extensions.getByType<AppExtension>().configure()
}
private fun Project.configureLibrary() {
androidDependencies()
baseKotlinModuleDependencies()
extensions.getByType<LibraryExtension>().configure()
}
private fun Project.configureWithKotlinPlugin() {
baseKotlinDependencies()
tasks.withType<KotlinCompile>().configureEach {
this.kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
}
private fun BaseExtension.configure() {
setCompileSdkVersion(ProjectConfig.compileSdkVersion)
with(defaultConfig) {
minSdk = ProjectConfig.minSdkVersion
targetSdk = ProjectConfig.targetSdkVersion
vectorDrawables.useSupportLibrary = true
}
with(compileOptions) {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
isCoreLibraryDesugaringEnabled = true
}
}
private fun Project.androidDependencies() {
commonAndroidDependencies()
}
private fun Project.commonAndroidDependencies() {
dependencies {
add("coreLibraryDesugaring", Dependencies.Tools.desugarJdkLibs)
}
}
private const val IMPLEMENTATION = "implementation"
private const val LINT_CHECKS = "lintChecks"
private fun Project.baseKotlinDependencies() {
dependencies {
add(IMPLEMENTATION, Dependencies.Base.kotlin)
add(IMPLEMENTATION, Dependencies.Base.kotlinReflect)
}
}
private fun Project.baseKotlinModuleDependencies() {
dependencies {
add(LINT_CHECKS, project(Dependencies.Modules.Base.customLint))
}
}
So how can I have the Gradle plugin works for the both places?
Thanks!
I'm trying to run local server with KTOR and to cover it with tests. I wrote some code and after writing some tests, the tests successfully raised the local server and passed. However, if I try to start a local server, I get this error
Exception in thread "main" java.lang.AbstractMethodError: Receiver
class io.ktor.server.engine.ApplicationEngineEnvironmentReloading does
not define or inherit an implementation of the resolved method
'abstract boolean getDevelopmentMode()' of interface
io.ktor.application.ApplicationEnvironment.
I attach the code and the stack trace from below
server.kt
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.gson.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
gson()
}
routing {
val controller = Controller()
get("/converter{from}{to}") {
try {
val fromCurrency = call.request.queryParameters["from"]
val toCurrency = call.request.queryParameters["to"]
val rate = controller.converter(fromCurrency, toCurrency)
val response = Response(
"1 $fromCurrency = $rate $toCurrency",
null
)
call.respond(HttpStatusCode.OK, response)
} catch (e: ControllerException) {
val response = Response(
null,
e.message
)
call.respond(HttpStatusCode.BadRequest, response)
}
}
get {
call.respond(HttpStatusCode.NotFound, Response())
}
}
}
#Serializable
data class Response(
#SerialName("converterResponse")
val converterResponse: String? = null,
#SerialName("errorMessage")
val errorMessage: String? = null
)
converterTest.kt
import com.google.gson.Gson
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.Test
import kotlin.test.assertEquals
class ConverterTest {
#Test
fun `Identical Correct Currencies`() {
withTestApplication(Application::module) {
handleRequest(HttpMethod.Get, "/converter?from=USD&to=USD").apply {
assertEquals(HttpStatusCode.OK, response.status())
val expectedResponse = Response("1 USD = 1 USD")
assertEquals(
Gson().toJson(expectedResponse),
response.content
)
}
}
}
}
stacktrace
Exception in thread "main" java.lang.AbstractMethodError: Receiver class io.ktor.server.engine.ApplicationEngineEnvironmentReloading does not define or inherit an implementation of the resolved method 'abstract boolean getDevelopmentMode()' of interface io.ktor.application.ApplicationEnvironment.
at io.ktor.application.Application.<init>(Application.kt:20)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:269)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:125)
at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:245)
at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:126)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:26)
at ServerKt.main(server.kt:11)
build.gradle
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.5.30" // or kotlin("multiplatform") or any other kotlin plugin
application
}
group = "me.admin"
version = "1.0-SNAPSHOT"
repositories {
jcenter()
mavenCentral()
maven { url = uri("https://dl.bintray.com/kotlin/kotlinx") }
maven { url = uri("https://dl.bintray.com/kotlin/ktor") }
}
dependencies {
val kotlin_version = "1.5.30"
val ktor_version = "1.6.3"
implementation("io.ktor:ktor-server-netty:1.4.0")
implementation("io.ktor:ktor-client-cio:1.4.0")
implementation("io.ktor:ktor-html-builder:1.4.0")
implementation("io.ktor:ktor-client-serialization:1.3.2-1.4-M2")
implementation("org.jetbrains.kotlinx:kotlinx-html-jvm:0.7.2")
implementation("org.slf4j:slf4j-api:2.0.0-alpha5")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC")
implementation(kotlin("stdlib-jdk8"))
testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
testImplementation("io.ktor:ktor-server-test-host:$ktor_version")
implementation("io.ktor:ktor-gson:$ktor_version")
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
application {
mainClassName = "ServerKt"
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
jvmTarget = "1.8"
}
val compileTestKotlin: KotlinCompile by tasks
compileTestKotlin.kotlinOptions {
jvmTarget = "1.8"
}
The dependency io.ktor:ktor-server-netty:1.4.0 causes the AbstractMethodError. To fix it just use the same version for all Ktor dependencies:
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("io.ktor:ktor-client-cio:$ktor_version")
implementation("io.ktor:ktor-html-builder:$ktor_version")
implementation("io.ktor:ktor-client-serialization:$ktor_version")
https://github.com/reticent-monolith/winds_server is the github repo if anyone finds it easier looking there.
I'm trying to use KMongo and Ktor with Kotlin's Serialization module but creating the MongoClient results in the following exception:
java.lang.ClassCastException: class org.litote.kmongo.serialization.SerializationCodecRegistry cannot be cast to class org.bson.codecs.configuration.CodecProvider (org.litote.kmongo.serialization.SerializationCodecRegistry and org.bson.codecs.configuration.CodecProvider are in unnamed module of loader 'app')
at org.litote.kmongo.service.ClassMappingTypeService$DefaultImpls.codecRegistry(ClassMappingTypeService.kt:83)
at org.litote.kmongo.serialization.SerializationClassMappingTypeService.codecRegistry(SerializationClassMappingTypeService.kt:40)
at org.litote.kmongo.serialization.SerializationClassMappingTypeService.coreCodecRegistry(SerializationClassMappingTypeService.kt:97)
at org.litote.kmongo.service.ClassMappingType.coreCodecRegistry(ClassMappingType.kt)
at org.litote.kmongo.service.ClassMappingTypeService$DefaultImpls.codecRegistry$default(ClassMappingTypeService.kt:79)
at org.litote.kmongo.KMongo.configureRegistry$kmongo_core(KMongo.kt:79)
at org.litote.kmongo.KMongo.createClient(KMongo.kt:70)
at org.litote.kmongo.KMongo.createClient(KMongo.kt:57)
at org.litote.kmongo.KMongo.createClient(KMongo.kt:47)
at org.litote.kmongo.KMongo.createClient(KMongo.kt:39)
at com.reticentmonolith.repo.MongoDispatchRepo.<init>(MongoDispatchRepo.kt:11)
at com.reticentmonolith.ApplicationKt.<clinit>(Application.kt:14)
... 23 more
Am I missing something in my build.gradle?
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}
}
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.5.10'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.5.10'
id 'application'
}
group 'com.reticentmonolith'
version '0.0.1-SNAPSHOT'
mainClassName = "io.ktor.server.netty.EngineMain"
sourceSets {
main.kotlin.srcDirs = main.java.srcDirs = ['src']
test.kotlin.srcDirs = test.java.srcDirs = ['test']
main.resources.srcDirs = ['resources']
test.resources.srcDirs = ['testresources']
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
// KOTLIN
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
// KTOR
implementation "io.ktor:ktor-server-netty:$ktor_version"
implementation "ch.qos.logback:logback-classic:$logback_version"
implementation "io.ktor:ktor-server-core:$ktor_version"
testImplementation "io.ktor:ktor-server-tests:$ktor_version"
implementation "io.ktor:ktor-serialization:$ktor_version"
// MONGO
implementation group: 'org.mongodb', name: 'mongo-java-driver', version: '3.12.8'
// KOTLINX SERIALIZATION
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1"
// KMONGO
implementation 'org.litote.kmongo:kmongo-serialization:4.2.7'
implementation group: 'org.litote.kmongo', name: 'kmongo-id-serialization', version: '4.2.7'
// KBSON (optional dependency for KMONGO and Serialization)
implementation "com.github.jershell:kbson:0.4.4"
}
Here's my MongoClient class:
import com.mongodb.client.MongoDatabase
import com.reticentmonolith.models.Dispatch
import java.time.LocalDate
import org.litote.kmongo.*
class MongoDispatchRepo: DispatchRepoInterface {
private val client = KMongo.createClient()
private val database: MongoDatabase = client.getDatabase("zw")
private val windsData = database.getCollection<Dispatch>("winds")
override fun createDispatch(dispatch: Dispatch) {
windsData.insertOne(dispatch)
}
override fun getAllDispatches(): Map<String, List<Dispatch>> {
val list = windsData.find().toList()
return mapOf("dispatches" to list)
}
override fun getDispatchesByDate(date: LocalDate): Map<String, List<Dispatch>> {
return mapOf("dispatches" to windsData.find(Dispatch::date eq date).toList())
}
override fun getDispatchesByDateRange(start: LocalDate, end: LocalDate): Map<String, List<Dispatch>> {
return mapOf("dispatches" to windsData.find(Dispatch::date gte(start), Dispatch::date lte(end)).toList())
}
override fun getDispatchById(id: Id<Dispatch>): Dispatch? {
return windsData.findOneById(id)
}
override fun updateDispatchById(id: Id<Dispatch>, update: Dispatch): Boolean {
val oldDispatch = getDispatchById(id)
if (oldDispatch != null) {
update.date = oldDispatch.date
update._id = oldDispatch._id
windsData.updateOneById(id, update)
return true
}
return false
}
override fun updateLastDispatch(update: Dispatch): Boolean {
val lastDispatch = getLastDispatch() ?: return false
update.date = lastDispatch.date
update._id = lastDispatch._id
windsData.updateOneById(lastDispatch._id, update)
return true
}
override fun deleteDispatchById(id: Id<Dispatch>) {
windsData.deleteOne(Dispatch::_id eq id)
}
override fun getLastDispatch(): Dispatch? {
val todaysDispatches = getDispatchesByDate(LocalDate.now())
if (todaysDispatches.isEmpty()) return null
return todaysDispatches["dispatches"]?.last()
}
override fun addSpeedsToLastDispatch(line4: Int?, line3: Int?, line2: Int?, line1: Int?) {
val lastDispatch = getLastDispatch() ?: return
lastDispatch.riders.get(4)?.speed = line4
lastDispatch.riders.get(3)?.speed = line3
lastDispatch.riders.get(2)?.speed = line2
lastDispatch.riders.get(1)?.speed = line1
updateLastDispatch(lastDispatch)
}
fun purgeDatabase() {
windsData.deleteMany(Dispatch::comment eq "")
}
}
And my Application.kt for Ktor:
package com.reticentmonolith
import com.reticentmonolith.models.createExampleDispatches
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.http.*
import com.reticentmonolith.repo.MongoDispatchRepo
import io.ktor.features.*
import io.ktor.serialization.*
import kotlinx.serialization.json.Json
import org.litote.kmongo.id.serialization.IdKotlinXSerializationModule
val repo = MongoDispatchRepo()
fun main(args: Array<String>) = io.ktor.server.netty.EngineMain.main(args)
#Suppress("unused") // Referenced in application.conf
#kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
json(
Json { serializersModule = IdKotlinXSerializationModule },
contentType = ContentType.Application.Json
)
}
repo.purgeDatabase()
val dispatchList = repo.getAllDispatches()["dispatches"]
if (dispatchList != null && dispatchList.isEmpty()) {
createExampleDispatches(0).forEach {
repo.createDispatch(it)
println("######## date: ${it.date} ################")
}
}
routing {
get("/dispatches/") {
call.response.status(HttpStatusCode.OK)
val dispatches = repo.getAllDispatches()
println("Dispatches from Mongo: $dispatches")
println("Dispatches encoded for response: $dispatches")
}
}
}
And finally the class being serialized:
package com.reticentmonolith.models
import com.reticentmonolith.serializers.DateSerializer
import com.reticentmonolith.serializers.TimeSerializer
import kotlinx.serialization.Contextual
import org.litote.kmongo.*
import kotlinx.serialization.Serializable
import java.time.LocalDate
import java.time.LocalTime
#Serializable
data class Dispatch(
var riders: MutableMap<Int, #Contextual Rider?> = mutableMapOf(
1 to null,
2 to null,
3 to null,
4 to null
),
var comment: String = "",
var wind_degrees: Int,
var wind_speed: Double,
var winds_instructor: String,
var bt_radio: String,
var _id: #Contextual Id<Dispatch> = newId(),
// #Serializable(with=DateSerializer::class)
#Contextual var date: LocalDate = LocalDate.now(),
// #Serializable(with=TimeSerializer::class)
#Contextual var time: LocalTime = LocalTime.now()
)
fun createExampleDispatches(amount: Int): Collection<Dispatch> {
val dispatches = mutableListOf<Dispatch>()
for (i in 0..amount) {
dispatches.add(Dispatch(
bt_radio = "BT Instructor",
winds_instructor = "Winds Instructor",
wind_speed = 20.5,
wind_degrees = 186
).apply {
this.riders[2] = Rider(67, front_slider = Slider.BLACK, trolley = 125)
this.riders[3] = Rider(112, front_slider = Slider.NEW_RED, rear_slider = Slider.YELLOW, trolley = 34)
})
}
return dispatches
}
Any help would be hugely appreciated :) Thanks!
I am attempting to use kotlinx.serialization in a multiplatform (JVM/JS) project.
When I add #Serializable annotation to some data classes in some class in common module:
#Serializable
data class User(
val user: String
)
The build succeeds without errors, but it doesn't look like the encoders/decoders are generated.
In build/generated-src I don't see any related kotlin files which provide the encodeToString extension function, and when I try to use something like:
JSON.encodeToString(User(login = "X"))
I get an Unresolved reference error:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun <reified T> StringFormat.encodeToString(value: TypeVariable(T)): String defined in kotlinx.serialization
Any help to resolve this would be appreciated. Thanks in advance.
My build.gradle.kts:
import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin
import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpack
import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpackConfig
/* buildscript {
dependencies {
val kotlinVersion: String by System.getProperties()
classpath(kotlin("serialization", version = kotlinVersion))
}
} */
plugins {
val kotlinVersion: String by System.getProperties()
kotlin("multiplatform") version kotlinVersion
id("kotlinx-serialization") version kotlinVersion
val kvisionVersion: String by System.getProperties()
id("kvision") version kvisionVersion
}
version = "1.0.0-SNAPSHOT"
group = "tech.lorefnon"
repositories {
mavenCentral()
jcenter()
maven { url = uri("https://dl.bintray.com/kotlin/kotlin-eap") }
maven { url = uri("https://kotlin.bintray.com/kotlinx") }
maven { url = uri("https://dl.bintray.com/kotlin/kotlin-js-wrappers") }
maven { url = uri("https://dl.bintray.com/rjaros/kotlin") }
maven { url = uri("https://repo.spring.io/milestone") }
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") }
mavenLocal()
}
// Versions
val kotlinVersion: String by System.getProperties()
val kvisionVersion: String by System.getProperties()
val ktorVersion: String by project
val logbackVersion: String by project
val commonsCodecVersion: String by project
val webDir = file("src/frontendMain/web")
val mainClassName = "io.ktor.server.netty.EngineMain"
kotlin {
jvm("backend") {
compilations.all {
kotlinOptions {
jvmTarget = "1.8"
freeCompilerArgs = listOf("-Xjsr305=strict")
}
}
}
js("frontend") {
browser {
runTask {
outputFileName = "main.bundle.js"
sourceMaps = false
devServer = KotlinWebpackConfig.DevServer(
open = false,
port = 3000,
proxy = mapOf(
"/kv/*" to "http://localhost:8080",
"/login" to "http://localhost:8080",
"/logout" to "http://localhost:8080",
"/kvws/*" to mapOf("target" to "ws://localhost:8080", "ws" to true)
),
contentBase = listOf("$buildDir/processedResources/frontend/main")
)
}
webpackTask {
outputFileName = "main.bundle.js"
}
testTask {
useKarma {
useChromeHeadless()
}
}
}
binaries.executable()
}
sourceSets {
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
api("pl.treksoft:kvision-server-ktor:$kvisionVersion")
implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.3")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1")
}
kotlin.srcDir("build/generated-src/common")
kotlin.srcDir("src/commonMain/kotlin")
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val backendMain by getting {
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation(kotlin("reflect"))
implementation("com.auth0:java-jwt:3.11.0")
implementation("io.ktor:ktor-server-netty:$ktorVersion")
implementation("io.ktor:ktor-auth:$ktorVersion")
implementation("io.ktor:ktor-auth-jwt:$ktorVersion")
implementation("ch.qos.logback:logback-classic:$logbackVersion")
implementation("commons-codec:commons-codec:$commonsCodecVersion")
implementation("org.redisson:redisson:3.14.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.4.2")
}
}
val backendTest by getting {
dependencies {
implementation(kotlin("test"))
implementation(kotlin("test-junit"))
}
}
val frontendMain by getting {
resources.srcDir(webDir)
dependencies {
implementation("pl.treksoft:kvision:$kvisionVersion")
implementation("pl.treksoft:kvision-redux:${kvisionVersion}")
implementation("pl.treksoft:kvision-bootstrap:$kvisionVersion")
implementation("pl.treksoft:kvision-bootstrap-select:$kvisionVersion")
implementation("pl.treksoft:kvision-datacontainer:$kvisionVersion")
implementation("pl.treksoft:kvision-bootstrap-dialog:$kvisionVersion")
implementation("pl.treksoft:kvision-fontawesome:$kvisionVersion")
implementation("pl.treksoft:kvision-i18n:$kvisionVersion")
implementation(npm("redux-logger", "3.0.6"))
}
kotlin.srcDir("build/generated-src/frontend")
}
val frontendTest by getting {
dependencies {
implementation(kotlin("test-js"))
implementation("pl.treksoft:kvision-testutils:$kvisionVersion:tests")
}
}
}
}
fun getNodeJsBinaryExecutable(): String {
val nodeDir = NodeJsRootPlugin.apply(project).nodeJsSetupTaskProvider.get().destination
val isWindows = System.getProperty("os.name").toLowerCase().contains("windows")
val nodeBinDir = if (isWindows) nodeDir else nodeDir.resolve("bin")
val command = NodeJsRootPlugin.apply(project).nodeCommand
val finalCommand = if (isWindows && command == "node") "node.exe" else command
return nodeBinDir.resolve(finalCommand).absolutePath
}
afterEvaluate {
tasks {
getByName("frontendProcessResources", Copy::class) {
dependsOn("compileKotlinFrontend")
exclude("**/*.pot")
doLast("Convert PO to JSON") {
destinationDir.walkTopDown().filter {
it.isFile && it.extension == "po"
}.forEach {
exec {
executable = getNodeJsBinaryExecutable()
args(
"$buildDir/js/node_modules/gettext.js/bin/po2json",
it.absolutePath,
"${it.parent}/${it.nameWithoutExtension}.json"
)
println("Converted ${it.name} to ${it.nameWithoutExtension}.json")
}
it.delete()
}
}
}
create("frontendArchive", Jar::class).apply {
dependsOn("frontendBrowserProductionWebpack")
group = "package"
archiveAppendix.set("frontend")
val distribution =
project.tasks.getByName("frontendBrowserProductionWebpack", KotlinWebpack::class).destinationDirectory!!
from(distribution) {
include("*.*")
}
from(webDir)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
into("/assets")
inputs.files(distribution, webDir)
outputs.file(archiveFile)
manifest {
attributes(
mapOf(
"Implementation-Title" to rootProject.name,
"Implementation-Group" to rootProject.group,
"Implementation-Version" to rootProject.version,
"Timestamp" to System.currentTimeMillis()
)
)
}
}
getByName("backendProcessResources", Copy::class) {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
getByName("backendJar").group = "package"
create("jar", Jar::class).apply {
dependsOn("frontendArchive", "backendJar")
group = "package"
manifest {
attributes(
mapOf(
"Implementation-Title" to rootProject.name,
"Implementation-Group" to rootProject.group,
"Implementation-Version" to rootProject.version,
"Timestamp" to System.currentTimeMillis(),
"Main-Class" to mainClassName
)
)
}
val dependencies = configurations["backendRuntimeClasspath"].filter { it.name.endsWith(".jar") } +
project.tasks["backendJar"].outputs.files +
project.tasks["frontendArchive"].outputs.files
dependencies.forEach {
if (it.isDirectory) from(it) else from(zipTree(it))
}
exclude("META-INF/*.RSA", "META-INF/*.SF", "META-INF/*.DSA")
inputs.files(dependencies)
outputs.file(archiveFile)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
create("backendRun", JavaExec::class) {
dependsOn("compileKotlinBackend")
group = "run"
main = mainClassName
classpath =
configurations["backendRuntimeClasspath"] + project.tasks["compileKotlinBackend"].outputs.files +
project.tasks["backendProcessResources"].outputs.files
workingDir = buildDir
}
getByName("compileKotlinBackend") {
dependsOn("compileKotlinMetadata")
}
getByName("compileKotlinFrontend") {
dependsOn("compileKotlinMetadata")
}
}
}
And gradle.properties:
javaVersion=1.8
#Plugins
systemProp.kotlinVersion=1.4.20
systemProp.serializationVersion=1.0.1
#Dependencies
systemProp.kvisionVersion=3.17.2
ktorVersion=1.4.3
commonsCodecVersion=1.10
logbackVersion=1.2.3
kotlin.mpp.stability.nowarn=true
kotlin.js.compiler=legacy
org.gradle.jvmargs=-Xmx2g
And settings.gradle.kts:
pluginManagement {
repositories {
mavenCentral()
jcenter()
maven { url = uri("https://plugins.gradle.org/m2/") }
maven { url = uri("https://dl.bintray.com/kotlin/kotlin-eap") }
maven { url = uri("https://kotlin.bintray.com/kotlinx") }
maven { url = uri("https://dl.bintray.com/rjaros/kotlin") }
mavenLocal()
}
resolutionStrategy {
eachPlugin {
when {
requested.id.id == "kotlinx-serialization" -> useModule("org.jetbrains.kotlin:kotlin-serialization:${requested.version}")
requested.id.id == "kvision" -> useModule("pl.treksoft:kvision-gradle-plugin:${requested.version}")
}
}
}
}
rootProject.name = "test"
I often face same problem. You just need to add import:
import kotlinx.serialization.encodeToString
You probably don't want to add import manually, I usually start typing encodeToStr and, wait suggestions to appear and choose encodeToString(value: T), this will add needed import.
I believe it's a bug that IDE don't give you a suggestion to import, and give us this error instead.
I’ve been struggling with this issue since days but can’t find any solution so I hope I can get any help here.
I created a Multiplatform project with Mobile Application template from IntelliJ IDEA 2020.2.1 and since project setup androidMain and AndroidTest folders are not recognised as module. This seems not to be a problem when launching androidApp task or PackForXcode as references to expect/actual definitions are resolved but idea suggestions shows anyway how androidMain reference seems to be wrong as reference seems to be resolved from parent vpayConnectLib module as per screenshot.
I use a standard android() target
When launching compileDebugAndroidTestKotlinAndroid task this error is highlighted
I tried to create new projects with different templates but androidMain and androidTest folders are not considered module since the beginning with all projects template
Is this a know bug or I am doing something wrong? Here’s root project gradle file with versions I am using
Hre's my root project gradle file:
buildscript {
repositories {
gradlePluginPortal()
jcenter()
google()
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.0")
classpath("com.android.tools.build:gradle:4.0.1")
classpath("com.squareup.sqldelight:gradle-plugin:1.4.3")
classpath("org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.8")
}
}
group = "com.retailinmotion"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
and here's shared library gradle file
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
id("com.android.library")
id("kotlin-android-extensions")
id("com.squareup.sqldelight")
id("org.sonarqube")
jacoco
}
group = "com.retailinmotion"
version = "1.0-SNAPSHOT"
repositories {
gradlePluginPortal()
google()
jcenter()
mavenCentral()
}
sqldelight {
database("vPayConnectDatabase") {
packageName = "com.retailinmotion.vpayconnect"
sourceFolders = listOf("sqldelight")
}
}
task<JacocoReport>("jacocoTestReport") {
dependsOn("testDebugUnitTest")
reports {
xml.isEnabled = true
csv.isEnabled = false
html.isEnabled = true
}
sourceDirectories.setFrom(files(fileTree("../vPayConnectLib")))
classDirectories.setFrom(files(fileTree("build/tmp/kotlin-classes/debug")))
executionData.setFrom(file("build/jacoco/testDebugUnitTest.exec"))
}
sonarqube {
properties {
property("sonar.sourceEncoding", "UTF-8")
property("sonar.java.coveragePlugin", "jacoco")
property("sonar.sources", "src/commonMain/kotlin, src/iosMain/kotlin, src/androidMain/kotlin")
property("sonar.tests", "src/commonTest/kotlin, src/iosTest/kotlin, src/androidTest/kotlin")
property("sonar.binaries", "build/tmp/kotlin-classes/debug")
property("sonar.java.binaries", "build/tmp/kotlin-classes/debug")
property("sonar.java.test.binaries", "build/tmp/kotlin-classes/debugUnitTest")
property("sonar.junit.reportPaths", "build/test-results/testDebugUnitTest")
property("sonar.jacoco.reportPaths", "build/jacoco/testDebugUnitTest.exec")
property("sonar.coverage.jacoco.xmlReportPaths", "build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml")
}
}
kotlin {
android()
iosArm64("ios") {
binaries {
framework {
baseName = "vPayConnectLib"
}
}
compilations["main"].cinterops {
//import Datecs library
val datecs by creating {
packageName ("com.retailinmotion.datecs")
defFile = file("$projectDir/src/iosMain/c_interop/Datecs.def")
includeDirs ("$projectDir/src/iosMain/c_interop/Datecs/")
}
//import Datecs Utils library
val datecsutils by creating {
packageName ("com.retailinmotion.datecsutils")
defFile = file("$projectDir/src/iosMain/c_interop/DatecsUtils.def")
includeDirs ("$projectDir/src/iosMain/c_interop/DatecsUtils/")
}
//import Magtek library
val magtek by creating {
packageName ("com.retailinmotion.magtek")
defFile = file("$projectDir/src/iosMain/c_interop/Magtek.def")
includeDirs ("$projectDir/src/iosMain/c_interop/Magtek")
}
}
}
iosX64(){
binaries {
framework {
baseName = "vPayConnectLib"
}
}
compilations["main"].cinterops {
//import Datecs library
val datecs by creating {
packageName ("com.retailinmotion.datecs")
defFile = file("$projectDir/src/iosMain/c_interop/Datecs.def")
includeDirs ("$projectDir/src/iosMain/c_interop/Datecs/")
}
//import Datecs Utils library
val datecsutils by creating {
packageName ("com.retailinmotion.datecsutils")
defFile = file("$projectDir/src/iosMain/c_interop/DatecsUtils.def")
includeDirs ("$projectDir/src/iosMain/c_interop/DatecsUtils/")
}
//import Magtek library
val magtek by creating {
packageName ("com.retailinmotion.magtek")
defFile = file("$projectDir/src/iosMain/c_interop/Magtek.def")
includeDirs ("$projectDir/src/iosMain/c_interop/Magtek")
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.squareup.sqldelight:runtime:1.4.3")
}
}
val commonTest by getting {
dependsOn(commonMain)
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
implementation("org.jetbrains.kotlin:kotlin-test-junit:1.4.10")
}
}
val androidMain by getting {
dependencies {
implementation("androidx.core:core-ktx:1.3.1")
implementation("com.squareup.sqldelight:android-driver:1.4.3")
}
}
val androidTest by getting {
dependsOn(androidMain)
}
val iosMain by getting {
dependencies {
implementation("com.squareup.sqldelight:native-driver:1.4.3")
}
}
val iosTest by getting {
dependsOn(iosMain)
}
val iosX64Main by getting {
dependsOn(iosMain)
}
val iosX64Test by getting {
dependsOn(iosTest)
}
}
tasks {
register("universalFramework", org.jetbrains.kotlin.gradle.tasks.FatFrameworkTask::class) {
val debugMode = "DEBUG"
val mode = System.getenv("CONFIGURATION") ?: debugMode
baseName = "vPayConnectLib"
val iosArm64Framework = iosArm64("ios").binaries.getFramework(mode)
val iosX64Framework = iosX64().binaries.getFramework(mode)
from(
iosArm64Framework,
iosX64Framework
)
destinationDir = buildDir.resolve("xcode-universal-framework")
group = "Universal framework"
description = "Builds a universal (fat) $mode framework"
dependsOn(iosArm64Framework.linkTask)
dependsOn(iosX64Framework.linkTask)
}
}
}
android {
compileSdkVersion(29)
defaultConfig {
minSdkVersion(24)
targetSdkVersion(29)
versionCode = 1
versionName = "1.0"
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
}
}
dependencies {
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
}
}
val packForXcode by tasks.creating(Sync::class) {
group = "build"
val mode = System.getenv("CONFIGURATION") ?: "DEBUG"
val framework = kotlin.targets.getByName<KotlinNativeTarget>("ios").binaries.getFramework(mode)
inputs.property("mode", mode)
dependsOn(framework.linkTask)
val targetDir = File(buildDir, "xcode-frameworks")
from({ framework.outputDirectory })
into(targetDir)
}
tasks.getByName("build").dependsOn(packForXcode)
Any help is appreciated,
Thanks