diff options
author | Robert Jaros <rjaros@finn.pl> | 2019-02-01 11:27:39 +0100 |
---|---|---|
committer | Robert Jaros <rjaros@finn.pl> | 2019-02-01 11:27:39 +0100 |
commit | ab2b183792f061f1292f77931ca2a36c62986141 (patch) | |
tree | f16e5523214b21ab960e3ec5f69ac6fb29475841 /kvision-modules/kvision-server-ktor/src/main | |
parent | da4ce7d161db9aca034e8224ca697bb831c58ad9 (diff) | |
download | kvision-ab2b183792f061f1292f77931ca2a36c62986141.tar.gz kvision-ab2b183792f061f1292f77931ca2a36c62986141.tar.bz2 kvision-ab2b183792f061f1292f77931ca2a36c62986141.zip |
New module for server-side interface with ktor framework.
Diffstat (limited to 'kvision-modules/kvision-server-ktor/src/main')
4 files changed, 581 insertions, 0 deletions
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>("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<KVServiceManager<*>>) + +/** + * 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<T : Any> actual constructor(val serviceClass: KClass<T>) : ServiceManager { + + companion object { + val LOG: Logger = LoggerFactory.getLogger(KVServiceManager::class.java.name) + } + + val postRequests: MutableMap<String, suspend (ApplicationCall) -> Unit> = mutableMapOf() + val putRequests: MutableMap<String, suspend (ApplicationCall) -> Unit> = mutableMapOf() + val deleteRequests: MutableMap<String, suspend (ApplicationCall) -> Unit> = mutableMapOf() + val optionsRequests: MutableMap<String, suspend (ApplicationCall) -> 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 <reified RET> 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<JsonRpcRequest>() + 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 <reified PAR, reified RET> 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<JsonRpcRequest>() + if (jsonRpcRequest.params.size == 1) { + val param = getParameter<PAR>(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 <reified PAR1, reified PAR2, reified RET> 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<JsonRpcRequest>() + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) + val param2 = getParameter<PAR2>(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 <reified PAR1, reified PAR2, reified PAR3, reified RET> 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<JsonRpcRequest>() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 3) { + val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) + val param2 = getParameter<PAR2>(jsonRpcRequest.params[1]) + val param3 = getParameter<PAR3>(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 <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> 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<JsonRpcRequest>() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 4) { + val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) + val param2 = getParameter<PAR2>(jsonRpcRequest.params[1]) + val param3 = getParameter<PAR3>(jsonRpcRequest.params[2]) + val param4 = getParameter<PAR4>(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 <reified PAR1, reified PAR2, reified PAR3, + reified PAR4, reified PAR5, reified RET> 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<JsonRpcRequest>() + @Suppress("MagicNumber") + if (jsonRpcRequest.params.size == 5) { + val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) + val param2 = getParameter<PAR2>(jsonRpcRequest.params[1]) + val param3 = getParameter<PAR3>(jsonRpcRequest.params[2]) + val param4 = getParameter<PAR4>(jsonRpcRequest.params[3]) + val param5 = getParameter<PAR5>(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<RemoteSelectOption> + ) { + val routeDef = "route${this::class.simpleName}${counter++}" + addRoute(RpcHttpMethod.POST, "/kv/$routeDef") { call -> + val service = call.injector.getInstance(serviceClass.java) + val jsonRpcRequest = call.receive<JsonRpcRequest>() + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter<String?>(jsonRpcRequest.params[0]) + val param2 = getParameter<String?>(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 <reified T> 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<Date>( + { row, c -> Date(row.timestamp(c).time) }, + { Timestamp(it.time) } +) + +val kvTableConfig = TableConfiguration( + converters = standardConverters + reifiedConverter(DateConverter), + namingConvention = camelToLowerUnderscore +) |