From ab2b183792f061f1292f77931ca2a36c62986141 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Fri, 1 Feb 2019 11:27:39 +0100 Subject: New module for server-side interface with ktor framework. --- kvision-modules/kvision-server-ktor/build.gradle | 28 ++ .../kotlin/pl/treksoft/kvision/remote/KVModules.kt | 96 +++++ .../kotlin/pl/treksoft/kvision/remote/KVServer.kt | 35 ++ .../pl/treksoft/kvision/remote/KVServiceManager.kt | 400 +++++++++++++++++++++ .../main/kotlin/pl/treksoft/kvision/types/Date.kt | 50 +++ 5 files changed, 609 insertions(+) create mode 100644 kvision-modules/kvision-server-ktor/build.gradle create mode 100644 kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt create mode 100644 kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt create mode 100644 kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt create mode 100644 kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/types/Date.kt (limited to 'kvision-modules') diff --git a/kvision-modules/kvision-server-ktor/build.gradle b/kvision-modules/kvision-server-ktor/build.gradle new file mode 100644 index 00000000..b38349a0 --- /dev/null +++ b/kvision-modules/kvision-server-ktor/build.gradle @@ -0,0 +1,28 @@ +apply plugin: 'kotlin-platform-jvm' +apply plugin: 'kotlinx-serialization' + +dependencies { + expectedBy project(":kvision-modules:kvision-common-types") + expectedBy project(":kvision-modules:kvision-common-remote") + 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 "io.ktor:ktor-server-core:$ktorVersion" + compile "io.ktor:ktor-jackson:$ktorVersion" + compile "com.google.inject:guice:$guiceVersion" + compile "org.pac4j:pac4j-core:$pac4jVersion" + compile "com.github.andrewoma.kwery:mapper:$kweryVersion" + 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") +} + +compileKotlin { + targetCompatibility = javaVersion + sourceCompatibility = javaVersion + kotlinOptions { + jvmTarget = javaVersion + } +} diff --git a/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt new file mode 100644 index 00000000..eb57f7d7 --- /dev/null +++ b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVModules.kt @@ -0,0 +1,96 @@ +/* + * 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.Injector +import com.google.inject.Module +import io.ktor.application.Application +import io.ktor.application.ApplicationCall +import io.ktor.application.ApplicationCallPipeline +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpMethod +import io.ktor.http.content.default +import io.ktor.http.content.resources +import io.ktor.http.content.static +import io.ktor.jackson.jackson +import io.ktor.request.httpMethod +import io.ktor.request.uri +import io.ktor.routing.routing +import io.ktor.util.AttributeKey +import pl.treksoft.kvision.types.KV_JSON_DATE_FORMAT +import java.text.SimpleDateFormat + +fun Application.kvision(vararg modules: Module) { + install(ContentNegotiation) { + jackson { + dateFormat = SimpleDateFormat(KV_JSON_DATE_FORMAT) + } + } + routing { + static("/") { + resources("assets") + default("index.html") + } + } + + val injector = Guice.createInjector(MainModule(this), *modules) + val kvServer = injector.getInstance(KVServer::class.java) + + intercept(ApplicationCallPipeline.Features) { + call.attributes.put(InjectorKey, injector.createChildInjector(CallModule(call))) + } + + intercept(ApplicationCallPipeline.Call) { + val routeUri = call.request.uri + if (routeUri.startsWith("/kv/")) { + kvServer.services.mapNotNull { + when (call.request.httpMethod) { + HttpMethod.Post -> it.postRequests[routeUri] + HttpMethod.Put -> it.putRequests[routeUri] + HttpMethod.Delete -> it.deleteRequests[routeUri] + HttpMethod.Options -> it.optionsRequests[routeUri] + else -> null + } + }.firstOrNull()?.invoke(call) + } + } +} + +val InjectorKey = AttributeKey("injector") + +val ApplicationCall.injector: Injector get() = attributes[InjectorKey] + +class CallModule(private val call: ApplicationCall) : AbstractModule() { + override fun configure() { + bind(ApplicationCall::class.java).toInstance(call) + } +} + +class MainModule(private val application: Application) : AbstractModule() { + override fun configure() { + bind(Application::class.java).toInstance(application) + } +} diff --git a/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt new file mode 100644 index 00000000..81d6ee34 --- /dev/null +++ b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt @@ -0,0 +1,35 @@ +/* + * 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 org.pac4j.core.profile.CommonProfile +import kotlinx.coroutines.async as coroutinesAsync + +/** + * A Ktor based server. + */ +actual open class KVServer(val services: List>) + +/** + * A user profile. + */ +actual typealias Profile = CommonProfile diff --git a/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt new file mode 100644 index 00000000..ecf2d290 --- /dev/null +++ b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/remote/KVServiceManager.kt @@ -0,0 +1,400 @@ +/* + * 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.module.kotlin.jacksonObjectMapper +import io.ktor.application.ApplicationCall +import io.ktor.request.receive +import io.ktor.response.respond +import kotlinx.coroutines.ExperimentalCoroutinesApi +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import pl.treksoft.kvision.types.KV_JSON_DATE_FORMAT +import java.text.SimpleDateFormat +import kotlin.reflect.KClass + +/** + * Multiplatform service manager for Ktor. + */ +@UseExperimental(ExperimentalCoroutinesApi::class) +actual open class KVServiceManager actual constructor(val serviceClass: KClass) : ServiceManager { + + companion object { + val LOG: Logger = LoggerFactory.getLogger(KVServiceManager::class.java.name) + } + + val postRequests: MutableMap Unit> = mutableMapOf() + val putRequests: MutableMap Unit> = mutableMapOf() + val deleteRequests: MutableMap Unit> = mutableMapOf() + val optionsRequests: MutableMap Unit> = mutableMapOf() + + val mapper = jacksonObjectMapper().apply { + dateFormat = SimpleDateFormat(KV_JSON_DATE_FORMAT) + } + var counter: Int = 0 + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param route a route + * @param method a HTTP method + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.() -> RET, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + try { + val result = function.invoke(service) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } + } + + /** + * Binds a given route with a function of the receiver. + * @param function a function of the receiver + * @param route a route + * @param method a HTTP method + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR) -> RET, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + if (jsonRpcRequest.params.size == 1) { + val param = getParameter(jsonRpcRequest.params[0]) + try { + val result = function.invoke(service, param) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } else { + call.respond( + 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 route a route + * @param method a HTTP method + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2) -> RET, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + try { + val result = function.invoke(service, param1, param2) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } else { + call.respond( + 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 route a route + * @param method a HTTP method + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3) -> RET, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + @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]) + try { + val result = function.invoke(service, param1, param2, param3) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } else { + call.respond( + 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 route a route + * @param method a HTTP method + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4) -> RET, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + @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]) + try { + val result = function.invoke(service, param1, param2, param3, param4) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } else { + call.respond( + 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 route a route + * @param method a HTTP method + */ + @Suppress("TooGenericExceptionCaught") + protected actual inline fun bind( + noinline function: suspend T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> RET, + route: String?, + method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + @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]) + try { + val result = function.invoke(service, param1, param2, param3, param4, param5) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } else { + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = "Invalid parameters" + ) + ) + } + } + } + + /** + * Binds a given function of the receiver as a select options source + * @param function a function of the receiver + */ + @Suppress("TooGenericExceptionCaught") + protected actual fun bind( + function: T.(String?, String?) -> List + ) { + val routeDef = "route${this::class.simpleName}${counter++}" + addRoute(RpcHttpMethod.POST, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive() + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter(jsonRpcRequest.params[0]) + val param2 = getParameter(jsonRpcRequest.params[1]) + try { + val result = function.invoke(service, param1, param2) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + } + } else { + call.respond( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = "Invalid parameters" + ) + ) + } + } + } + + fun addRoute( + method: RpcHttpMethod, + path: String, + handler: suspend (ApplicationCall) -> Unit + ) { + when (method) { + RpcHttpMethod.POST -> postRequests[path] = handler + RpcHttpMethod.PUT -> putRequests[path] = handler + RpcHttpMethod.DELETE -> deleteRequests[path] = handler + RpcHttpMethod.OPTIONS -> optionsRequests[path] = handler + } + } + + protected inline fun getParameter(str: String?): T { + return str?.let { + if (T::class == String::class) { + str as T + } else { + mapper.readValue(str, T::class.java) + } + } ?: null as T + } + + /** + * Applies all defined routes to the given server. + */ + actual fun applyRoutes(k: KVServer) {} +} diff --git a/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/types/Date.kt b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/types/Date.kt new file mode 100644 index 00000000..57853c8b --- /dev/null +++ b/kvision-modules/kvision-server-ktor/src/main/kotlin/pl/treksoft/kvision/types/Date.kt @@ -0,0 +1,50 @@ +/* + * 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.github.andrewoma.kwery.mapper.SimpleConverter +import com.github.andrewoma.kwery.mapper.TableConfiguration +import com.github.andrewoma.kwery.mapper.reifiedConverter +import com.github.andrewoma.kwery.mapper.standardConverters +import com.github.andrewoma.kwery.mapper.util.camelToLowerUnderscore +import java.sql.Timestamp +import java.text.SimpleDateFormat + +actual val KV_DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss" + +actual val KV_JSON_DATE_FORMAT = "yyyy-MM-dd HH:mm:ssZ" + +actual typealias Date = java.util.Date + +actual fun String.toDateF(format: String): Date = SimpleDateFormat(format).parse(this) + +actual fun Date.toStringF(format: String): String = SimpleDateFormat(format).format(this) + +object DateConverter : SimpleConverter( + { row, c -> Date(row.timestamp(c).time) }, + { Timestamp(it.time) } +) + +val kvTableConfig = TableConfiguration( + converters = standardConverters + reifiedConverter(DateConverter), + namingConvention = camelToLowerUnderscore +) -- cgit