From 9e243a469ae6544e8cf523ad09b959f541c3f565 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Wed, 11 Mar 2020 16:18:17 +0100 Subject: Upgrade to Kotlin 1.3.70 + other dependencies (Coroutinse, Serialization, Spring Boot) Major refactoring of build architecture. --- .../kvision-server-javalin/build.gradle | 30 -- .../kvision-server-javalin/build.gradle.kts | 69 +++ .../pl/treksoft/kvision/remote/KVServiceManager.kt | 122 +++++ .../pl/treksoft/kvision/remote/KVServiceManager.kt | 160 ++++++ .../kotlin/pl/treksoft/kvision/remote/KVModules.kt | 54 ++ .../pl/treksoft/kvision/remote/KVServiceManager.kt | 565 +++++++++++++++++++++ .../treksoft/kvision/remote/SessionInterfaces.kt | 43 ++ .../kotlin/pl/treksoft/kvision/remote/KVModules.kt | 54 -- .../pl/treksoft/kvision/remote/KVServiceManager.kt | 565 --------------------- .../treksoft/kvision/remote/SessionInterfaces.kt | 43 -- .../main/kotlin/pl/treksoft/kvision/types/Date.kt | 200 -------- .../kotlin/pl/treksoft/kvision/types/Decimal.kt | 47 -- 12 files changed, 1013 insertions(+), 939 deletions(-) delete mode 100644 kvision-modules/kvision-server-javalin/build.gradle create mode 100644 kvision-modules/kvision-server-javalin/build.gradle.kts create mode 100644 kvision-modules/kvision-server-javalin/src/commonMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt create mode 100644 kvision-modules/kvision-server-javalin/src/jsMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt create mode 100644 kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVModules.kt create mode 100644 kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt create mode 100644 kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt delete mode 100644 kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt delete mode 100644 kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt delete mode 100644 kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt delete mode 100644 kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Date.kt delete mode 100644 kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Decimal.kt (limited to 'kvision-modules/kvision-server-javalin') diff --git a/kvision-modules/kvision-server-javalin/build.gradle b/kvision-modules/kvision-server-javalin/build.gradle deleted file mode 100644 index 4664b5d9..00000000 --- a/kvision-modules/kvision-server-javalin/build.gradle +++ /dev/null @@ -1,30 +0,0 @@ -apply plugin: 'kotlin-platform-jvm' -apply plugin: 'kotlinx-serialization' - -dependencies { - expectedBy project(":kvision-modules:kvision-common-types") - expectedBy project(":kvision-modules:kvision-common-remote") - expectedBy project(":kvision-modules:kvision-common-annotations") - compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" - compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serializationVersion" - compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion" - compile "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutinesVersion" - compile "io.javalin:javalin:$javalinVersion" - compile "com.google.inject:guice:$guiceVersion" - compile "com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonModuleKotlinVersion" - testCompile "org.jetbrains.kotlin:kotlin-test:$kotlinVersion" - testCompile project(":kvision-modules:kvision-common-types") - testCompile project(":kvision-modules:kvision-common-remote") - testCompile project(":kvision-modules:kvision-common-annotations") -} - -compileKotlin { - targetCompatibility = javaVersion - sourceCompatibility = javaVersion - kotlinOptions { - jvmTarget = javaVersion - } -} diff --git a/kvision-modules/kvision-server-javalin/build.gradle.kts b/kvision-modules/kvision-server-javalin/build.gradle.kts new file mode 100644 index 00000000..daaae81c --- /dev/null +++ b/kvision-modules/kvision-server-javalin/build.gradle.kts @@ -0,0 +1,69 @@ +buildscript { + extra.set("production", (findProperty("prod") ?: findProperty("production") ?: "false") == "true") +} + +plugins { + kotlin("multiplatform") + id("kotlinx-serialization") + id("maven-publish") +} + +repositories() + +// Versions +val kotlinVersion: String by System.getProperties() +val serializationVersion: String by project +val coroutinesVersion: String by project +val javalinVersion: String by project +val guiceVersion: String by project +val jacksonModuleKotlinVersion: String by project + +kotlin { + kotlinJsTargets() + kotlinJvmTargets() + sourceSets { + val commonMain by getting { + dependencies { + implementation(kotlin("stdlib-common")) + api(project(":kvision-modules:kvision-common-annotations")) + api(project(":kvision-modules:kvision-common-types")) + api(project(":kvision-modules:kvision-common-remote")) + api(project(":kvision-modules:kvision-common-remote")) + api("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serializationVersion") + api("org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutinesVersion") + } + } + val jsMain by getting { + dependencies { + implementation(kotlin("stdlib-js")) + api("org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serializationVersion") + api("org.jetbrains.kotlinx:kotlinx-coroutines-core-js:$coroutinesVersion") + } + } + val jvmMain by getting { + dependsOn(commonMain) + dependencies { + implementation(kotlin("stdlib")) + implementation(kotlin("stdlib-jdk8")) + implementation(kotlin("reflect")) + api("org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serializationVersion") + api("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion") + api("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutinesVersion") + api("io.javalin:javalin:$javalinVersion") + api("com.google.inject:guice:$guiceVersion") + api("com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonModuleKotlinVersion") + } + } + } +} + +publishing { + publications.withType { + if (name == "kotlinMultiplatform") artifactId = "kvision-server-javalin" + pom { + defaultPom() + } + } +} + +setupPublication() diff --git a/kvision-modules/kvision-server-javalin/src/commonMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt b/kvision-modules/kvision-server-javalin/src/commonMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt new file mode 100644 index 00000000..19da13c0 --- /dev/null +++ b/kvision-modules/kvision-server-javalin/src/commonMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package pl.treksoft.kvision.remote + +import kotlinx.coroutines.channels.ReceiveChannel +import kotlinx.coroutines.channels.SendChannel +import kotlin.reflect.KClass + +/** + * Multiplatform service manager. + */ +expect open class KVServiceManager(serviceClass: KClass) { + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected inline fun bind( + noinline function: suspend T.() -> RET, + method: HttpMethod = HttpMethod.POST, + route: String? = null + ) + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected inline fun bind( + noinline function: suspend T.(PAR) -> RET, + method: HttpMethod = HttpMethod.POST, + route: String? = null + ) + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected inline fun bind( + noinline function: suspend T.(PAR1, PAR2) -> RET, + method: HttpMethod = HttpMethod.POST, + route: String? = null + ) + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3) -> RET, + method: HttpMethod = HttpMethod.POST, + route: String? = null + ) + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4) -> RET, + method: HttpMethod = HttpMethod.POST, + route: String? = null + ) + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> RET, + method: HttpMethod = HttpMethod.POST, + route: String? = null + ) + + /** + * Binds a given function of the receiver as a tabulator component source + * @param function a function of the receiver + */ + protected inline fun bindTabulatorRemote( + noinline function: suspend T.(Int?, Int?, List?, List?, String?) -> RemoteData + ) + + /** + * Binds a given function of the receiver as a web socket connection + * @param function a function of the receiver + */ + protected inline fun bind( + noinline function: suspend T.(ReceiveChannel, SendChannel) -> Unit, + route: String? = null + ) +} diff --git a/kvision-modules/kvision-server-javalin/src/jsMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt b/kvision-modules/kvision-server-javalin/src/jsMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt new file mode 100644 index 00000000..23da6ac5 --- /dev/null +++ b/kvision-modules/kvision-server-javalin/src/jsMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +import kotlinx.coroutines.channels.ReceiveChannel +import kotlinx.coroutines.channels.SendChannel +import kotlin.reflect.KClass + +/** + * Multiplatform service manager. + */ +actual open class KVServiceManager actual constructor(serviceClass: KClass): KVServiceMgr { + + protected val calls: MutableMap> = mutableMapOf() + var counter: Int = 0 + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.() -> RET, + method: HttpMethod, route: String? + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", method) + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.(PAR) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", method) + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", method) + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", method) + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", method) + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", method) + } + + /** + * Binds a given function of the receiver as a tabulator component source + * @param function a function of the receiver + */ + protected actual inline fun bindTabulatorRemote( + noinline function: suspend T.(Int?, Int?, List?, List?, String?) -> RemoteData + ) { + val routeDef = "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kv/$routeDef", HttpMethod.POST) + } + + /** + * Binds a given web socket connetion with a function of the receiver. + * @param function a function of the receiver + * @param route a web socket route + */ + protected actual inline fun bind( + noinline function: suspend T.(ReceiveChannel, SendChannel) -> Unit, + route: String? + ) { + val routeDef = "route${this::class.simpleName}${counter++}" + calls[function.toString().replace("\\s".toRegex(), "")] = Pair("/kvws/$routeDef", HttpMethod.POST) + } + + /** + * Returns the map of defined paths. + */ + override fun getCalls(): Map> = calls + +} diff --git a/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVModules.kt b/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVModules.kt new file mode 100644 index 00000000..aef6e2f2 --- /dev/null +++ b/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVModules.kt @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +import com.google.inject.AbstractModule +import com.google.inject.Guice +import com.google.inject.Module +import io.javalin.Javalin + +const val KV_INJECTOR_KEY = "pl.treksoft.kvision.injector.key" + +/** + * Initialization function for Javalin server. + */ +fun Javalin.kvisionInit(vararg modules: Module) { + config.addStaticFiles("/assets") + + @Suppress("SpreadOperator") + val injector = Guice.createInjector(MainModule(this), *modules) + + before { + it.attribute(KV_INJECTOR_KEY, injector) + } + wsBefore { ws -> + ws.onConnect { ctx -> + ctx.attribute(KV_INJECTOR_KEY, injector) + } + } +} + +internal class MainModule(private val javalin: Javalin) : AbstractModule() { + override fun configure() { + bind(Javalin::class.java).toInstance(javalin) + } +} diff --git a/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt b/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt new file mode 100644 index 00000000..e6428524 --- /dev/null +++ b/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.fasterxml.jackson.module.kotlin.readValue +import com.google.inject.Injector +import io.javalin.Javalin +import io.javalin.core.security.Role +import io.javalin.http.Context +import io.javalin.websocket.WsContext +import io.javalin.websocket.WsHandler +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.ReceiveChannel +import kotlinx.coroutines.channels.SendChannel +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.future.future +import kotlinx.coroutines.launch +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import pl.treksoft.kvision.types.* +import java.math.BigDecimal +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime +import kotlin.reflect.KClass + +/** + * Multiplatform service manager for Javalin. + */ +@Suppress("LargeClass", "TooManyFunctions") +@OptIn(ExperimentalCoroutinesApi::class) +actual open class KVServiceManager actual constructor(val serviceClass: KClass) { + + companion object { + val LOG: Logger = LoggerFactory.getLogger(KVServiceManager::class.java.name) + const val KV_WS_INCOMING_KEY = "pl.treksoft.kvision.ws.incoming.key" + const val KV_WS_OUTGOING_KEY = "pl.treksoft.kvision.ws.outgoing.key" + } + + val getRequests: MutableMap Unit> = mutableMapOf() + val postRequests: MutableMap Unit> = mutableMapOf() + val putRequests: MutableMap Unit> = mutableMapOf() + val deleteRequests: MutableMap Unit> = + mutableMapOf() + val optionsRequests: MutableMap Unit> = + mutableMapOf() + val webSocketRequests: MutableMap Unit> = + mutableMapOf() + + val mapper = jacksonObjectMapper().apply { + val module = SimpleModule() + module.addSerializer(LocalDateTime::class.java, LocalDateTimeSerializer()) + module.addSerializer(LocalDate::class.java, LocalDateSerializer()) + module.addSerializer(LocalTime::class.java, LocalTimeSerializer()) + module.addSerializer(OffsetDateTime::class.java, OffsetDateTimeSerializer()) + module.addSerializer(OffsetTime::class.java, OffsetTimeSerializer()) + module.addSerializer(BigDecimal::class.java, BigDecimalSerializer()) + module.addDeserializer(LocalDateTime::class.java, LocalDateTimeDeserializer()) + module.addDeserializer(LocalDate::class.java, LocalDateDeserializer()) + module.addDeserializer(LocalTime::class.java, LocalTimeDeserializer()) + module.addDeserializer(OffsetDateTime::class.java, OffsetDateTimeDeserializer()) + module.addDeserializer(OffsetTime::class.java, OffsetTimeDeserializer()) + module.addDeserializer(BigDecimal::class.java, BigDecimalDeserializer()) + this.registerModule(module) + } + var counter: Int = 0 + + /** + * @suppress internal function + */ + fun initializeService(service: T, ctx: Context) { + if (service is WithContext) { + service.ctx = ctx + } + if (service is WithHttpSession) { + service.httpSession = ctx.req.session + } + } + + /** + * @suppress internal function + */ + fun initializeWsService(service: T, wsCtx: WsContext) { + if (service is WithWsContext) { + service.wsCtx = wsCtx + } + if (service is WithWsSession) { + service.wsSession = wsCtx.session + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.() -> RET, + method: HttpMethod, route: String? + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = if (method == HttpMethod.GET) { + JsonRpcRequest(ctx.queryParam("id").get(), "", listOf()) + } else { + ctx.body() + } + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = ctx.body() + if (jsonRpcRequest.params.size == 1) { + val param = getParameter(jsonRpcRequest.params[0]) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service, param) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } else { + ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = ctx.body() + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service, param1, param2) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } else { + ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = ctx.body() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 3) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + val param3 = getParameter(jsonRpcRequest.params[2]) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service, param1, param2, param3) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } else { + ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = ctx.body() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 4) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + val param3 = getParameter(jsonRpcRequest.params[2]) + val param4 = getParameter(jsonRpcRequest.params[3]) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service, param1, param2, param3, param4) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } else { + ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param method a HTTP method + * @param route a route + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> RET, + method: HttpMethod, route: String? + ) { + if (method == HttpMethod.GET) + throw UnsupportedOperationException("GET method is only supported for methods without parameters") + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = ctx.body() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 5) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + val param3 = getParameter(jsonRpcRequest.params[2]) + val param4 = getParameter(jsonRpcRequest.params[3]) + val param5 = getParameter(jsonRpcRequest.params[4]) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service, param1, param2, param3, param4, param5) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } else { + ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + } + } + + /** + * Binds a given web socket connection with a function of the receiver. + * @param function a function of the receiver + * @param route a route + */ + protected actual inline fun bind( + noinline function: suspend T.(ReceiveChannel, SendChannel) -> Unit, + route: String? + ) { + val routeDef = "route${this::class.simpleName}${counter++}" + webSocketRequests["/kvws/$routeDef"] = { ws -> + ws.onConnect { ctx -> + val incoming = Channel() + val outgoing = Channel() + ctx.attribute(KV_WS_INCOMING_KEY, incoming) + ctx.attribute(KV_WS_OUTGOING_KEY, outgoing) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeWsService(service, ctx) + GlobalScope.launch { + coroutineScope { + launch(Dispatchers.IO) { + for (text in outgoing) { + ctx.send(text) + } + ctx.session.close() + } + launch { + val requestChannel = Channel() + val responseChannel = Channel() + coroutineScope { + launch { + for (p in incoming) { + val jsonRpcRequest = getParameter(p) + if (jsonRpcRequest.params.size == 1) { + val par = getParameter(jsonRpcRequest.params[0]) + requestChannel.send(par) + } + } + requestChannel.close() + } + launch(Dispatchers.IO) { + for (p in responseChannel) { + val text = mapper.writeValueAsString( + JsonRpcResponse( + id = 0, + result = mapper.writeValueAsString(p) + ) + ) + outgoing.send(text) + } + } + launch { + function.invoke(service, requestChannel, responseChannel) + if (!responseChannel.isClosedForReceive) responseChannel.close() + } + } + if (!outgoing.isClosedForReceive) outgoing.close() + } + } + } + } + ws.onClose { ctx -> + GlobalScope.launch { + val outgoing = ctx.attribute>(KV_WS_OUTGOING_KEY)!! + val incoming = ctx.attribute>(KV_WS_INCOMING_KEY)!! + outgoing.close() + incoming.close() + } + } + ws.onMessage { ctx -> + GlobalScope.launch { + val incoming = ctx.attribute>(KV_WS_INCOMING_KEY)!! + incoming.send(ctx.message()) + } + } + } + } + + /** + * Binds a given function of the receiver as a tabulator component source + * @param function a function of the receiver + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bindTabulatorRemote( + noinline function: suspend T.(Int?, Int?, List?, List?, String?) -> RemoteData + ) { + val routeDef = "route${this::class.simpleName}${counter++}" + addRoute(HttpMethod.POST, "/kv/$routeDef") { ctx -> + val jsonRpcRequest = ctx.body() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 5) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + val param3 = getParameter?>(jsonRpcRequest.params[2]) + @Suppress("MagicNumber") + val param4 = getParameter?>(jsonRpcRequest.params[3]) + @Suppress("MagicNumber") + val param5 = getParameter(jsonRpcRequest.params[4]) + val injector = ctx.attribute(KV_INJECTOR_KEY)!! + val service = injector.getInstance(serviceClass.java) + initializeService(service, ctx) + val future = GlobalScope.future { + try { + val result = function.invoke(service, param1, param2, param3, param4, param5) + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + } catch (e: Exception) { + if (e !is ServiceException) LOG.error(e.message, e) + JsonRpcResponse( + id = jsonRpcRequest.id, error = e.message ?: "Error", + exceptionType = e.javaClass.canonicalName + ) + } + } + ctx.json(future) + } else { + ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + } + } + + /** + * @suppress Internal method + */ + fun addRoute( + method: HttpMethod, + path: String, + handler: (Context) -> Unit + ) { + when (method) { + HttpMethod.GET -> getRequests[path] = handler + HttpMethod.POST -> postRequests[path] = handler + HttpMethod.PUT -> putRequests[path] = handler + HttpMethod.DELETE -> deleteRequests[path] = handler + HttpMethod.OPTIONS -> optionsRequests[path] = handler + } + } + + /** + * @suppress Internal method + */ + protected inline fun getParameter(str: String?): T { + return str?.let { + if (T::class == String::class) { + str as T + } else { + mapper.readValue(str) + } + } ?: null as T + } + +} + +/** + * A function to generate routes based on definitions from the service manager. + */ +fun Javalin.applyRoutes(serviceManager: KVServiceManager, roles: Set = setOf()) { + serviceManager.getRequests.forEach { (path, handler) -> + get(path, handler, roles) + } + serviceManager.postRequests.forEach { (path, handler) -> + post(path, handler, roles) + } + serviceManager.putRequests.forEach { (path, handler) -> + put(path, handler, roles) + } + serviceManager.deleteRequests.forEach { (path, handler) -> + delete(path, handler, roles) + } + serviceManager.optionsRequests.forEach { (path, handler) -> + options(path, handler, roles) + } + serviceManager.webSocketRequests.forEach { (path, handler) -> + ws(path, handler, roles) + } +} diff --git a/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt b/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt new file mode 100644 index 00000000..e44cc46f --- /dev/null +++ b/kvision-modules/kvision-server-javalin/src/jvmMain/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +import io.javalin.http.Context +import io.javalin.websocket.WsContext +import org.eclipse.jetty.websocket.api.Session +import javax.servlet.http.HttpSession + +interface WithContext { + var ctx: Context +} + +interface WithHttpSession { + var httpSession: HttpSession +} + +interface WithWsContext { + var wsCtx: WsContext +} + +interface WithWsSession { + var wsSession: Session +} diff --git a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt b/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt deleted file mode 100644 index aef6e2f2..00000000 --- a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017-present Robert Jaros - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package pl.treksoft.kvision.remote - -import com.google.inject.AbstractModule -import com.google.inject.Guice -import com.google.inject.Module -import io.javalin.Javalin - -const val KV_INJECTOR_KEY = "pl.treksoft.kvision.injector.key" - -/** - * Initialization function for Javalin server. - */ -fun Javalin.kvisionInit(vararg modules: Module) { - config.addStaticFiles("/assets") - - @Suppress("SpreadOperator") - val injector = Guice.createInjector(MainModule(this), *modules) - - before { - it.attribute(KV_INJECTOR_KEY, injector) - } - wsBefore { ws -> - ws.onConnect { ctx -> - ctx.attribute(KV_INJECTOR_KEY, injector) - } - } -} - -internal class MainModule(private val javalin: Javalin) : AbstractModule() { - override fun configure() { - bind(Javalin::class.java).toInstance(javalin) - } -} diff --git a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt b/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt deleted file mode 100644 index ffb2936b..00000000 --- a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt +++ /dev/null @@ -1,565 +0,0 @@ -/* - * Copyright (c) 2017-present Robert Jaros - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package pl.treksoft.kvision.remote - -import com.fasterxml.jackson.databind.module.SimpleModule -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.fasterxml.jackson.module.kotlin.readValue -import com.google.inject.Injector -import io.javalin.Javalin -import io.javalin.core.security.Role -import io.javalin.http.Context -import io.javalin.websocket.WsContext -import io.javalin.websocket.WsHandler -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.channels.ReceiveChannel -import kotlinx.coroutines.channels.SendChannel -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.future.future -import kotlinx.coroutines.launch -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import pl.treksoft.kvision.types.* -import java.math.BigDecimal -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.OffsetDateTime -import java.time.OffsetTime -import kotlin.reflect.KClass - -/** - * Multiplatform service manager for Javalin. - */ -@Suppress("LargeClass", "TooManyFunctions") -@UseExperimental(ExperimentalCoroutinesApi::class) -actual open class KVServiceManager actual constructor(val serviceClass: KClass) { - - companion object { - val LOG: Logger = LoggerFactory.getLogger(KVServiceManager::class.java.name) - const val KV_WS_INCOMING_KEY = "pl.treksoft.kvision.ws.incoming.key" - const val KV_WS_OUTGOING_KEY = "pl.treksoft.kvision.ws.outgoing.key" - } - - val getRequests: MutableMap Unit> = mutableMapOf() - val postRequests: MutableMap Unit> = mutableMapOf() - val putRequests: MutableMap Unit> = mutableMapOf() - val deleteRequests: MutableMap Unit> = - mutableMapOf() - val optionsRequests: MutableMap Unit> = - mutableMapOf() - val webSocketRequests: MutableMap Unit> = - mutableMapOf() - - val mapper = jacksonObjectMapper().apply { - val module = SimpleModule() - module.addSerializer(LocalDateTime::class.java, LocalDateTimeSerializer()) - module.addSerializer(LocalDate::class.java, LocalDateSerializer()) - module.addSerializer(LocalTime::class.java, LocalTimeSerializer()) - module.addSerializer(OffsetDateTime::class.java, OffsetDateTimeSerializer()) - module.addSerializer(OffsetTime::class.java, OffsetTimeSerializer()) - module.addSerializer(BigDecimal::class.java, BigDecimalSerializer()) - module.addDeserializer(LocalDateTime::class.java, LocalDateTimeDeserializer()) - module.addDeserializer(LocalDate::class.java, LocalDateDeserializer()) - module.addDeserializer(LocalTime::class.java, LocalTimeDeserializer()) - module.addDeserializer(OffsetDateTime::class.java, OffsetDateTimeDeserializer()) - module.addDeserializer(OffsetTime::class.java, OffsetTimeDeserializer()) - module.addDeserializer(BigDecimal::class.java, BigDecimalDeserializer()) - this.registerModule(module) - } - var counter: Int = 0 - - /** - * @suppress internal function - */ - fun initializeService(service: T, ctx: Context) { - if (service is WithContext) { - service.ctx = ctx - } - if (service is WithHttpSession) { - service.httpSession = ctx.req.session - } - } - - /** - * @suppress internal function - */ - fun initializeWsService(service: T, wsCtx: WsContext) { - if (service is WithWsContext) { - service.wsCtx = wsCtx - } - if (service is WithWsSession) { - service.wsSession = wsCtx.session - } - } - - /** - * Binds a given route with a function of the receiver. - * @param function a function of the receiver - * @param method a HTTP method - * @param route a route - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bind( - noinline function: suspend T.() -> RET, - method: HttpMethod, route: String? - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - addRoute(method, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = if (method == HttpMethod.GET) { - JsonRpcRequest(ctx.queryParam("id").get(), "", listOf()) - } else { - ctx.body() - } - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } - } - - /** - * Binds a given route with a function of the receiver. - * @param function a function of the receiver - * @param method a HTTP method - * @param route a route - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bind( - noinline function: suspend T.(PAR) -> RET, - method: HttpMethod, route: String? - ) { - if (method == HttpMethod.GET) - throw UnsupportedOperationException("GET method is only supported for methods without parameters") - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - addRoute(method, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = ctx.body() - if (jsonRpcRequest.params.size == 1) { - val param = getParameter(jsonRpcRequest.params[0]) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service, param) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } else { - ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } - } - - /** - * Binds a given route with a function of the receiver. - * @param function a function of the receiver - * @param method a HTTP method - * @param route a route - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bind( - noinline function: suspend T.(PAR1, PAR2) -> RET, - method: HttpMethod, route: String? - ) { - if (method == HttpMethod.GET) - throw UnsupportedOperationException("GET method is only supported for methods without parameters") - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - addRoute(method, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = ctx.body() - if (jsonRpcRequest.params.size == 2) { - val param1 = getParameter(jsonRpcRequest.params[0]) - val param2 = getParameter(jsonRpcRequest.params[1]) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service, param1, param2) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } else { - ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } - } - - /** - * Binds a given route with a function of the receiver. - * @param function a function of the receiver - * @param method a HTTP method - * @param route a route - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bind( - noinline function: suspend T.(PAR1, PAR2, PAR3) -> RET, - method: HttpMethod, route: String? - ) { - if (method == HttpMethod.GET) - throw UnsupportedOperationException("GET method is only supported for methods without parameters") - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - addRoute(method, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = ctx.body() - @Suppress("MagicNumber") - if (jsonRpcRequest.params.size == 3) { - val param1 = getParameter(jsonRpcRequest.params[0]) - val param2 = getParameter(jsonRpcRequest.params[1]) - val param3 = getParameter(jsonRpcRequest.params[2]) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service, param1, param2, param3) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } else { - ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } - } - - /** - * Binds a given route with a function of the receiver. - * @param function a function of the receiver - * @param method a HTTP method - * @param route a route - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bind( - noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4) -> RET, - method: HttpMethod, route: String? - ) { - if (method == HttpMethod.GET) - throw UnsupportedOperationException("GET method is only supported for methods without parameters") - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - addRoute(method, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = ctx.body() - @Suppress("MagicNumber") - if (jsonRpcRequest.params.size == 4) { - val param1 = getParameter(jsonRpcRequest.params[0]) - val param2 = getParameter(jsonRpcRequest.params[1]) - val param3 = getParameter(jsonRpcRequest.params[2]) - val param4 = getParameter(jsonRpcRequest.params[3]) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service, param1, param2, param3, param4) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } else { - ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } - } - - /** - * Binds a given route with a function of the receiver. - * @param function a function of the receiver - * @param method a HTTP method - * @param route a route - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bind( - noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> RET, - method: HttpMethod, route: String? - ) { - if (method == HttpMethod.GET) - throw UnsupportedOperationException("GET method is only supported for methods without parameters") - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - addRoute(method, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = ctx.body() - @Suppress("MagicNumber") - if (jsonRpcRequest.params.size == 5) { - val param1 = getParameter(jsonRpcRequest.params[0]) - val param2 = getParameter(jsonRpcRequest.params[1]) - val param3 = getParameter(jsonRpcRequest.params[2]) - val param4 = getParameter(jsonRpcRequest.params[3]) - val param5 = getParameter(jsonRpcRequest.params[4]) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service, param1, param2, param3, param4, param5) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } else { - ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } - } - - /** - * Binds a given web socket connection with a function of the receiver. - * @param function a function of the receiver - * @param route a route - */ - protected actual inline fun bind( - noinline function: suspend T.(ReceiveChannel, SendChannel) -> Unit, - route: String? - ) { - val routeDef = "route${this::class.simpleName}${counter++}" - webSocketRequests["/kvws/$routeDef"] = { ws -> - ws.onConnect { ctx -> - val incoming = Channel() - val outgoing = Channel() - ctx.attribute(KV_WS_INCOMING_KEY, incoming) - ctx.attribute(KV_WS_OUTGOING_KEY, outgoing) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeWsService(service, ctx) - GlobalScope.launch { - coroutineScope { - launch(Dispatchers.IO) { - for (text in outgoing) { - ctx.send(text) - } - ctx.session.close() - } - launch { - val requestChannel = Channel() - val responseChannel = Channel() - coroutineScope { - launch { - for (p in incoming) { - val jsonRpcRequest = getParameter(p) - if (jsonRpcRequest.params.size == 1) { - val par = getParameter(jsonRpcRequest.params[0]) - requestChannel.send(par) - } - } - requestChannel.close() - } - launch(Dispatchers.IO) { - for (p in responseChannel) { - val text = mapper.writeValueAsString( - JsonRpcResponse( - id = 0, - result = mapper.writeValueAsString(p) - ) - ) - outgoing.send(text) - } - } - launch { - function.invoke(service, requestChannel, responseChannel) - if (!responseChannel.isClosedForReceive) responseChannel.close() - } - } - if (!outgoing.isClosedForReceive) outgoing.close() - } - } - } - } - ws.onClose { ctx -> - GlobalScope.launch { - val outgoing = ctx.attribute>(KV_WS_OUTGOING_KEY)!! - val incoming = ctx.attribute>(KV_WS_INCOMING_KEY)!! - outgoing.close() - incoming.close() - } - } - ws.onMessage { ctx -> - GlobalScope.launch { - val incoming = ctx.attribute>(KV_WS_INCOMING_KEY)!! - incoming.send(ctx.message()) - } - } - } - } - - /** - * Binds a given function of the receiver as a tabulator component source - * @param function a function of the receiver - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun bindTabulatorRemote( - noinline function: suspend T.(Int?, Int?, List?, List?, String?) -> RemoteData - ) { - val routeDef = "route${this::class.simpleName}${counter++}" - addRoute(HttpMethod.POST, "/kv/$routeDef") { ctx -> - val jsonRpcRequest = ctx.body() - @Suppress("MagicNumber") - if (jsonRpcRequest.params.size == 5) { - val param1 = getParameter(jsonRpcRequest.params[0]) - val param2 = getParameter(jsonRpcRequest.params[1]) - val param3 = getParameter?>(jsonRpcRequest.params[2]) - @Suppress("MagicNumber") - val param4 = getParameter?>(jsonRpcRequest.params[3]) - @Suppress("MagicNumber") - val param5 = getParameter(jsonRpcRequest.params[4]) - val injector = ctx.attribute(KV_INJECTOR_KEY)!! - val service = injector.getInstance(serviceClass.java) - initializeService(service, ctx) - val future = GlobalScope.future { - try { - val result = function.invoke(service, param1, param2, param3, param4, param5) - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - } catch (e: Exception) { - if (e !is ServiceException) LOG.error(e.message, e) - JsonRpcResponse( - id = jsonRpcRequest.id, error = e.message ?: "Error", - exceptionType = e.javaClass.canonicalName - ) - } - } - ctx.json(future) - } else { - ctx.json(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } - } - - /** - * @suppress Internal method - */ - fun addRoute( - method: HttpMethod, - path: String, - handler: (Context) -> Unit - ) { - when (method) { - HttpMethod.GET -> getRequests[path] = handler - HttpMethod.POST -> postRequests[path] = handler - HttpMethod.PUT -> putRequests[path] = handler - HttpMethod.DELETE -> deleteRequests[path] = handler - HttpMethod.OPTIONS -> optionsRequests[path] = handler - } - } - - /** - * @suppress Internal method - */ - protected inline fun getParameter(str: String?): T { - return str?.let { - if (T::class == String::class) { - str as T - } else { - mapper.readValue(str) - } - } ?: null as T - } - -} - -/** - * A function to generate routes based on definitions from the service manager. - */ -fun Javalin.applyRoutes(serviceManager: KVServiceManager, roles: Set = setOf()) { - serviceManager.getRequests.forEach { (path, handler) -> - get(path, handler, roles) - } - serviceManager.postRequests.forEach { (path, handler) -> - post(path, handler, roles) - } - serviceManager.putRequests.forEach { (path, handler) -> - put(path, handler, roles) - } - serviceManager.deleteRequests.forEach { (path, handler) -> - delete(path, handler, roles) - } - serviceManager.optionsRequests.forEach { (path, handler) -> - options(path, handler, roles) - } - serviceManager.webSocketRequests.forEach { (path, handler) -> - ws(path, handler, roles) - } -} diff --git a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt b/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt deleted file mode 100644 index e44cc46f..00000000 --- a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/remote/SessionInterfaces.kt +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017-present Robert Jaros - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package pl.treksoft.kvision.remote - -import io.javalin.http.Context -import io.javalin.websocket.WsContext -import org.eclipse.jetty.websocket.api.Session -import javax.servlet.http.HttpSession - -interface WithContext { - var ctx: Context -} - -interface WithHttpSession { - var httpSession: HttpSession -} - -interface WithWsContext { - var wsCtx: WsContext -} - -interface WithWsSession { - var wsSession: Session -} diff --git a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Date.kt b/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Date.kt deleted file mode 100644 index 61f8ba58..00000000 --- a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Date.kt +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2017-present Robert Jaros - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package pl.treksoft.kvision.types - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.JsonParser -import com.fasterxml.jackson.databind.DeserializationContext -import com.fasterxml.jackson.databind.JsonDeserializer -import com.fasterxml.jackson.databind.JsonSerializer -import com.fasterxml.jackson.databind.SerializerProvider -import java.io.IOException -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.OffsetDateTime -import java.time.OffsetTime -import java.time.format.DateTimeFormatter -import java.time.format.DateTimeParseException - -actual typealias LocalDateTime = LocalDateTime - -actual typealias LocalDate = LocalDate - -actual typealias LocalTime = LocalTime - -actual typealias OffsetDateTime = OffsetDateTime - -actual typealias OffsetTime = OffsetTime - -fun String.toDateTimeF(): LocalDateTime = LocalDateTime.parse(this) - -fun String.toDateF(): LocalDate = LocalDate.parse(this) - -fun String.toTimeF(): LocalTime = LocalTime.parse(this) - -fun String.toOffsetDateTimeF(): OffsetDateTime = OffsetDateTime.parse(this) - -fun String.toOffsetTimeF(): OffsetTime = OffsetTime.parse(this) - -fun LocalDateTime.toStringF(): String = this.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) - -fun LocalDate.toStringF(): String = this.format(DateTimeFormatter.ISO_LOCAL_DATE) - -fun LocalTime.toStringF(): String = this.format(DateTimeFormatter.ISO_LOCAL_TIME) - -fun OffsetDateTime.toStringF(): String = this.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME) - -fun OffsetTime.toStringF(): String = this.format(DateTimeFormatter.ISO_OFFSET_TIME) - -class LocalDateTimeSerializer : JsonSerializer() { - @Throws(IOException::class) - override fun serialize(value: LocalDateTime, gen: JsonGenerator, provider: SerializerProvider) { - try { - val s = value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) - gen.writeString(s) - } catch (e: DateTimeParseException) { - System.err.println(e) - gen.writeString("") - } - } -} - -class LocalDateTimeDeserializer : JsonDeserializer() { - @Throws(IOException::class) - override fun deserialize(p: JsonParser, ctx: DeserializationContext): LocalDateTime? { - val str = p.text - try { - @Suppress("MagicNumber") - return LocalDateTime.parse(str.dropLast(6), DateTimeFormatter.ISO_LOCAL_DATE_TIME) - } catch (e: DateTimeParseException) { - System.err.println(e) - return null - } - } -} - -class LocalDateSerializer : JsonSerializer() { - @Throws(IOException::class) - override fun serialize(value: LocalDate, gen: JsonGenerator, provider: SerializerProvider) { - try { - val s = value.atStartOfDay().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) - gen.writeString(s) - } catch (e: DateTimeParseException) { - System.err.println(e) - gen.writeString("") - } - } -} - -class LocalDateDeserializer : JsonDeserializer() { - @Throws(IOException::class) - override fun deserialize(p: JsonParser, ctx: DeserializationContext): LocalDate? { - val str = p.text - try { - @Suppress("MagicNumber") - return LocalDate.parse(str.dropLast(6), DateTimeFormatter.ISO_LOCAL_DATE_TIME) - } catch (e: DateTimeParseException) { - System.err.println(e) - return null - } - } -} - -class LocalTimeSerializer : JsonSerializer() { - @Throws(IOException::class) - override fun serialize(value: LocalTime, gen: JsonGenerator, provider: SerializerProvider) { - try { - val s = value.atDate(LocalDate.now()).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) - gen.writeString(s) - } catch (e: DateTimeParseException) { - System.err.println(e) - gen.writeString("") - } - } -} - -class LocalTimeDeserializer : JsonDeserializer() { - @Throws(IOException::class) - override fun deserialize(p: JsonParser, ctx: DeserializationContext): LocalTime? { - val str = p.text - try { - @Suppress("MagicNumber") - return LocalTime.parse(str.dropLast(6), DateTimeFormatter.ISO_LOCAL_DATE_TIME) - } catch (e: DateTimeParseException) { - System.err.println(e) - return null - } - } -} - -class OffsetDateTimeSerializer : JsonSerializer() { - @Throws(IOException::class) - override fun serialize(value: OffsetDateTime, gen: JsonGenerator, provider: SerializerProvider) { - try { - val s = value.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME) - gen.writeString(s) - } catch (e: DateTimeParseException) { - System.err.println(e) - gen.writeString("") - } - } -} - -class OffsetDateTimeDeserializer : JsonDeserializer() { - @Throws(IOException::class) - override fun deserialize(p: JsonParser, ctx: DeserializationContext): OffsetDateTime? { - val str = p.text - return try { - OffsetDateTime.parse(str, DateTimeFormatter.ISO_OFFSET_DATE_TIME) - } catch (e: DateTimeParseException) { - System.err.println(e) - null - } - } -} - -class OffsetTimeSerializer : JsonSerializer() { - @Throws(IOException::class) - override fun serialize(value: OffsetTime, gen: JsonGenerator, provider: SerializerProvider) { - try { - val s = value.atDate(LocalDate.now()).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME) - gen.writeString(s) - } catch (e: DateTimeParseException) { - System.err.println(e) - gen.writeString("") - } - } -} - -class OffsetTimeDeserializer : JsonDeserializer() { - @Throws(IOException::class) - override fun deserialize(p: JsonParser, ctx: DeserializationContext): OffsetTime? { - val str = p.text - return try { - OffsetTime.parse(str, DateTimeFormatter.ISO_OFFSET_DATE_TIME) - } catch (e: DateTimeParseException) { - System.err.println(e) - null - } - } -} diff --git a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Decimal.kt b/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Decimal.kt deleted file mode 100644 index 1d37ae51..00000000 --- a/kvision-modules/kvision-server-javalin/src/main/kotlin/pl/treksoft/kvision/types/Decimal.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017-present Robert Jaros - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package pl.treksoft.kvision.types - -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.JsonParser -import com.fasterxml.jackson.databind.DeserializationContext -import com.fasterxml.jackson.databind.JsonDeserializer -import com.fasterxml.jackson.databind.JsonSerializer -import com.fasterxml.jackson.databind.SerializerProvider -import java.io.IOException -import java.math.BigDecimal - -actual typealias Decimal = BigDecimal - -class BigDecimalSerializer : JsonSerializer() { - @Throws(IOException::class) - override fun serialize(value: BigDecimal, gen: JsonGenerator, provider: SerializerProvider) { - gen.writeNumber(value.toDouble()) - } -} - -class BigDecimalDeserializer : JsonDeserializer() { - @Throws(IOException::class) - override fun deserialize(p: JsonParser, ctx: DeserializationContext): BigDecimal? { - return p.doubleValue.toBigDecimal() - } -} -- cgit