diff options
23 files changed, 2359 insertions, 816 deletions
diff --git a/build.gradle b/build.gradle index 35fa82c7..e1728313 100644 --- a/build.gradle +++ b/build.gradle @@ -161,7 +161,8 @@ dokka { 'kvision-modules/kvision-handlebars/src/main/kotlin', 'kvision-modules/kvision-i18n/src/main/kotlin', 'kvision-modules/kvision-common/src/main/kotlin', - 'kvision-modules/kvision-server-jooby/src/main/kotlin') + 'kvision-modules/kvision-server-jooby/src/main/kotlin', + 'kvision-modules/kvision-server-spring-boot/src/main/kotlin') classpath = [new File("dokka/kvision-dokka-helper.jar")] outputFormat = 'html' outputDirectory = "$buildDir/kdoc" diff --git a/gradle.properties b/gradle.properties index b65cd1d7..01af6f19 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ group=pl.treksoft version=0.0.18 -kotlinVersion=1.3.0-rc-146 +kotlinVersion=1.3.0-rc-190 javaVersion=1.8 coroutinesVersion=0.30.2-eap13 serializationVersion=0.8.1-rc13 @@ -9,6 +9,8 @@ dokkaVersion=0.9.17 detektVersion=1.0.0.RC9.2 junitVersion=4.12 joobyVersion=1.5.1 +springBootVersion=2.0.4.RELEASE +pac4jVersion=3.3.0 kweryVersion=0.17 dependencyManagementPluginVersion=1.0.4.RELEASE jacksonModuleKotlinVersion=2.9.7 diff --git a/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt b/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt new file mode 100644 index 00000000..dceae898 --- /dev/null +++ b/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt @@ -0,0 +1,109 @@ +/* + * 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.Deferred + +/** + * Multiplatform service manager for Jooby. + */ +expect open class JoobyServiceManager<T : Any>(service: T) : ServiceManager { + + /** + * 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 + */ + protected inline fun <reified RET> bind( + noinline function: T.(Request?) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR, reified RET> bind( + noinline function: T.(PAR, Request?) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified RET> bind( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * Applies all defined routes to the given server. + * @param k a server + */ + fun applyRoutes(k: KVServer) + +} diff --git a/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt index 07f60851..6f696475 100644 --- a/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt +++ b/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt @@ -21,8 +21,6 @@ */ package pl.treksoft.kvision.remote -import kotlinx.coroutines.Deferred - enum class RpcHttpMethod { POST, PUT, @@ -38,102 +36,10 @@ enum class HttpMethod { OPTIONS } -/** - * Multiplatform service manager. - */ -expect open class ServiceManager<out T>(service: T) { - /** - * 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 - * @param prefix an URL address prefix - */ - protected inline fun <reified RET> bind( - noinline function: T.(Request?) -> Deferred<RET>, - route: String? = null, - method: RpcHttpMethod = RpcHttpMethod.POST, - prefix: String = "/" - ) - - /** - * 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 - * @param prefix an URL address prefix - */ - protected inline fun <reified PAR, reified RET> bind( - noinline function: T.(PAR, Request?) -> Deferred<RET>, - route: String? = null, - method: RpcHttpMethod = RpcHttpMethod.POST, - prefix: String = "/" - ) - - /** - * 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 - * @param prefix an URL address prefix - */ - protected inline fun <reified PAR1, reified PAR2, reified RET> bind( - noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, - route: String? = null, - method: RpcHttpMethod = RpcHttpMethod.POST, - prefix: String = "/" - ) - - /** - * 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 - * @param prefix an URL address prefix - */ - protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( - noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, - route: String? = null, - method: RpcHttpMethod = RpcHttpMethod.POST, - prefix: String = "/" - ) - - /** - * 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 - * @param prefix an URL address prefix - */ - protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, - route: String? = null, - method: RpcHttpMethod = RpcHttpMethod.POST, - prefix: String = "/" - ) - - /** - * 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 - * @param prefix an URL address prefix - */ - protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, - route: String? = null, - method: RpcHttpMethod = RpcHttpMethod.POST, - prefix: String = "/" - ) - - /** - * Applies all defined routes to the given server. - * @param k a server - */ - fun applyRoutes(k: KVServer) - +interface ServiceManager { /** * Returns the map of defined paths. */ - fun getCalls(): Map<String, Pair<String, RpcHttpMethod>> + fun getCalls(): Map<String, Pair<String, RpcHttpMethod>> = mapOf() + } diff --git a/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt b/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt new file mode 100644 index 00000000..0e17d4e7 --- /dev/null +++ b/kvision-modules/kvision-common/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt @@ -0,0 +1,103 @@ +/* + * 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.Deferred +import kotlin.reflect.KClass + +/** + * Multiplatform service manager for Spring Boot. + */ +expect open class SpringServiceManager<T : Any>(serviceClass: KClass<T>) : ServiceManager { + + /** + * 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 + */ + protected inline fun <reified RET> bind( + noinline function: T.() -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR, reified RET> bind( + noinline function: T.(PAR) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified RET> bind( + noinline function: T.(PAR1, PAR2) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) + + /** + * 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 + */ + protected inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> Deferred<RET>, + route: String? = null, + method: RpcHttpMethod = RpcHttpMethod.POST + ) +} diff --git a/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt new file mode 100644 index 00000000..1d5cd926 --- /dev/null +++ b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt @@ -0,0 +1,313 @@ +/* + * 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 kotlinx.coroutines.Deferred +import kotlinx.coroutines.runBlocking +import org.jooby.Response +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import java.text.SimpleDateFormat + +/** + * Multiplatform service manager for Jooby. + */ +actual open class JoobyServiceManager<T : Any> actual constructor(val service: T) : ServiceManager { + + companion object { + val LOG: Logger = LoggerFactory.getLogger(JoobyServiceManager::class.java.name) + } + + protected val routes: MutableList<KVServer.() -> Unit> = mutableListOf() + val mapper = jacksonObjectMapper().apply { + dateFormat = SimpleDateFormat("YYYY-MM-DD HH:mm:ss") + } + 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: T.(Request?) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + routes.add { + call(method, "/kv/$routeDef") { req, res -> + val jsonRpcRequest = req.body(JsonRpcRequest::class.java) + try { + val result = runBlocking { function.invoke(service, req).await() } + res.send( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) + } + }.invoke(this) + } + } + + /** + * 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: T.(PAR, Request?) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + routes.add { + call(method, "/kv/$routeDef") { req, res -> + val jsonRpcRequest = req.body(JsonRpcRequest::class.java) + if (jsonRpcRequest.params.size == 1) { + val param = getParameter<PAR>(jsonRpcRequest.params[0]) + try { + val result = runBlocking { function.invoke(service, param, req).await() } + res.send( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) + } + } else { + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + }.invoke(this) + } + } + + /** + * 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: T.(PAR1, PAR2, Request?) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + routes.add { + call(method, "/kv/$routeDef") { req, res -> + val jsonRpcRequest = req.body(JsonRpcRequest::class.java) + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) + val param2 = getParameter<PAR2>(jsonRpcRequest.params[1]) + try { + val result = runBlocking { function.invoke(service, param1, param2, req).await() } + res.send( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) + } + } else { + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + }.invoke(this) + } + } + + /** + * 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: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + routes.add { + call(method, "/kv/$routeDef") { req, res -> + val jsonRpcRequest = req.body(JsonRpcRequest::class.java) + @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 = runBlocking { function.invoke(service, param1, param2, param3, req).await() } + res.send( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) + } + } else { + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + }.invoke(this) + } + } + + /** + * 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: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + routes.add { + call(method, "/kv/$routeDef") { req, res -> + val jsonRpcRequest = req.body(JsonRpcRequest::class.java) + @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 = + runBlocking { function.invoke(service, param1, param2, param3, param4, req).await() } + res.send( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) + } + } else { + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + }.invoke(this) + } + } + + /** + * 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: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + routes.add { + call(method, "/kv/$routeDef") { req, res -> + val jsonRpcRequest = req.body(JsonRpcRequest::class.java) + @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 = + runBlocking { + function.invoke(service, param1, param2, param3, param4, param5, req).await() + } + res.send( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) + } + } else { + res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) + } + }.invoke(this) + } + } + + fun call( + method: RpcHttpMethod, + path: String, + handler: (Request, Response) -> Unit + ): KVServer.() -> Unit { + return { + when (method) { + RpcHttpMethod.POST -> post(path, handler) + RpcHttpMethod.PUT -> put(path, handler) + RpcHttpMethod.DELETE -> delete(path, handler) + RpcHttpMethod.OPTIONS -> options(path, handler) + } + } + } + + @Suppress("TooGenericExceptionCaught") + 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. + * @param k a server + */ + actual fun applyRoutes(k: KVServer) { + routes.forEach { + it.invoke(k) + } + } + +} diff --git a/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt index 38edc1b8..1e19f394 100644 --- a/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt +++ b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt @@ -73,7 +73,7 @@ fun <RESP> Request?.async(block: (Request) -> RESP): Deferred<RESP> = this?.let /** * A helper extension function for asynchronous request processing with session. */ -fun <RESP> Request?.async(block: (Request, Session) -> RESP): Deferred<RESP> = this?.let { req -> +fun <RESP> Request?.asyncSession(block: (Request, Session) -> RESP): Deferred<RESP> = this?.let { req -> val session = req.session() GlobalScope.coroutinesAsync(Dispatchers.Unconfined) { block(req, session) @@ -83,10 +83,12 @@ fun <RESP> Request?.async(block: (Request, Session) -> RESP): Deferred<RESP> = t /** * A helper extension function for asynchronous request processing with session and user profile. */ -fun <RESP> Request?.async(block: (Request, Session, Profile) -> RESP): Deferred<RESP> = this?.let { req -> +fun <RESP> Request?.asyncAuth(block: (Request, Session, Profile) -> RESP): Deferred<RESP> = this?.let { req -> val session = req.session() - val profile = req.require(CommonProfile::class.java) - GlobalScope.coroutinesAsync(Dispatchers.Unconfined) { - block(req, session, profile) + val profile = req.require(CommonProfile::class.java) as CommonProfile? + profile?.let { + GlobalScope.coroutinesAsync(Dispatchers.Unconfined) { + block(req, session, profile) + } } -} ?: throw IllegalStateException("Request not set!") +} ?: throw IllegalStateException("Request or profile not set!") diff --git a/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt deleted file mode 100644 index 3091ce26..00000000 --- a/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt +++ /dev/null @@ -1,350 +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.module.kotlin.jacksonObjectMapper -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.runBlocking -import org.jooby.Response -import org.jooby.Status -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import java.text.SimpleDateFormat - -/** - * Multiplatform service manager. - */ -actual open class ServiceManager<out T> actual constructor(val service: T) { - - companion object { - val LOG: Logger = LoggerFactory.getLogger(ServiceManager::class.java.name) - } - - protected val routes: MutableList<KVServer.() -> Unit> = mutableListOf() - val mapper = jacksonObjectMapper().apply { - dateFormat = SimpleDateFormat("YYYY-MM-DD HH:mm:ss") - } - 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 - * @param prefix an URL address prefix - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun <reified RET> bind( - noinline function: T.(Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - routes.add { - call(method, "$prefix$routeDef") { req, res -> - if (service != null) { - val jsonRpcRequest = req.body(JsonRpcRequest::class.java) - try { - val result = runBlocking { function.invoke(service, req).await() } - res.send( - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - ) - } catch (e: Exception) { - LOG.error(e.message, e) - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) - } - } else { - res.status(Status.SERVER_ERROR) - } - }.invoke(this) - } - } - - /** - * 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 - * @param prefix an URL address prefix - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun <reified PAR, reified RET> bind( - noinline function: T.(PAR, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - routes.add { - call(method, "$prefix$routeDef") { req, res -> - if (service != null) { - val jsonRpcRequest = req.body(JsonRpcRequest::class.java) - if (jsonRpcRequest.params.size == 1) { - val param = getParameter<PAR>(jsonRpcRequest.params[0]) - try { - val result = runBlocking { function.invoke(service, param, req).await() } - res.send( - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - ) - } catch (e: Exception) { - LOG.error(e.message, e) - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) - } - } else { - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } else { - res.status(Status.SERVER_ERROR) - } - }.invoke(this) - } - } - - /** - * 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 - * @param prefix an URL address prefix - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( - noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - routes.add { - call(method, "$prefix$routeDef") { req, res -> - if (service != null) { - val jsonRpcRequest = req.body(JsonRpcRequest::class.java) - if (jsonRpcRequest.params.size == 2) { - val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) - val param2 = getParameter<PAR2>(jsonRpcRequest.params[1]) - try { - val result = runBlocking { function.invoke(service, param1, param2, req).await() } - res.send( - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - ) - } catch (e: Exception) { - LOG.error(e.message, e) - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) - } - } else { - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } else { - res.status(Status.SERVER_ERROR) - } - }.invoke(this) - } - } - - /** - * 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 - * @param prefix an URL address prefix - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( - noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - routes.add { - call(method, "$prefix$routeDef") { req, res -> - if (service != null) { - val jsonRpcRequest = req.body(JsonRpcRequest::class.java) - @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 = runBlocking { function.invoke(service, param1, param2, param3, req).await() } - res.send( - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - ) - } catch (e: Exception) { - LOG.error(e.message, e) - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) - } - } else { - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } else { - res.status(Status.SERVER_ERROR) - } - }.invoke(this) - } - } - - /** - * 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 - * @param prefix an URL address prefix - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - routes.add { - call(method, "$prefix$routeDef") { req, res -> - if (service != null) { - val jsonRpcRequest = req.body(JsonRpcRequest::class.java) - @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 = - runBlocking { function.invoke(service, param1, param2, param3, param4, req).await() } - res.send( - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - ) - } catch (e: Exception) { - LOG.error(e.message, e) - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) - } - } else { - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } else { - res.status(Status.SERVER_ERROR) - } - }.invoke(this) - } - } - - /** - * 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 - * @param prefix an URL address prefix - */ - @Suppress("TooGenericExceptionCaught") - protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, - reified PAR4, reified PAR5, reified RET> bind( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, - route: String?, - method: RpcHttpMethod, - prefix: String - ) { - val routeDef = route ?: "route${this::class.simpleName}${counter++}" - routes.add { - call(method, "$prefix$routeDef") { req, res -> - if (service != null) { - val jsonRpcRequest = req.body(JsonRpcRequest::class.java) - @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 = - runBlocking { - function.invoke(service, param1, param2, param3, param4, param5, req).await() - } - res.send( - JsonRpcResponse( - id = jsonRpcRequest.id, - result = mapper.writeValueAsString(result) - ) - ) - } catch (e: Exception) { - LOG.error(e.message, e) - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = e.message ?: "Error")) - } - } else { - res.send(JsonRpcResponse(id = jsonRpcRequest.id, error = "Invalid parameters")) - } - } else { - res.status(Status.SERVER_ERROR) - } - }.invoke(this) - } - } - - fun call( - method: RpcHttpMethod, - path: String, - handler: (Request, Response) -> Unit - ): KVServer.() -> Unit { - return { - when (method) { - RpcHttpMethod.POST -> post(path, handler) - RpcHttpMethod.PUT -> put(path, handler) - RpcHttpMethod.DELETE -> delete(path, handler) - RpcHttpMethod.OPTIONS -> options(path, handler) - } - } - } - - @Suppress("TooGenericExceptionCaught") - 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. - * @param k a server - */ - actual fun applyRoutes(k: KVServer) { - routes.forEach { - it.invoke(k) - } - } - - /** - * Returns the list of defined bindings. - * Not used on the jvm platform. - */ - actual fun getCalls(): Map<String, Pair<String, RpcHttpMethod>> = mapOf() -} diff --git a/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt new file mode 100644 index 00000000..462b3777 --- /dev/null +++ b/kvision-modules/kvision-server-jooby/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt @@ -0,0 +1,116 @@ +/* + * 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.Deferred +import kotlin.reflect.KClass + +/** + * Multiplatform service manager for Spring Boot. + * Not to be used in this module. + */ +actual open class SpringServiceManager<T : Any> actual constructor(val serviceClass: KClass<T>) : ServiceManager { + /** + * 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 + */ + protected actual inline fun <reified RET> bind( + noinline function: T.() -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Spring Boot integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR, reified RET> bind( + noinline function: T.(PAR) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Spring Boot integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( + noinline function: T.(PAR1, PAR2) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Spring Boot integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Spring Boot integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Spring Boot integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Spring Boot integration.") + } + +} diff --git a/kvision-modules/kvision-server-spring-boot/build.gradle b/kvision-modules/kvision-server-spring-boot/build.gradle new file mode 100644 index 00000000..d235f214 --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/build.gradle @@ -0,0 +1,25 @@ +apply plugin: 'kotlin-platform-jvm' +apply plugin: 'kotlinx-serialization' + +dependencies { + expectedBy project(":kvision-modules:kvision-common") + compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" + compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serializationVersion" + compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion" + compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" + compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" + compile "org.springframework.boot:spring-boot-starter:$springBootVersion" + compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion" + 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") +} + +compileKotlin { + kotlinOptions { + freeCompilerArgs = ["-Xjsr305=strict"] + jvmTarget = "1.8" + } +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt new file mode 100644 index 00000000..75410e07 --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.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.Deferred + +/** + * Multiplatform service manager for Jooby. + * Not to be used in this module. + */ +actual open class JoobyServiceManager<T : Any> actual constructor(val service: T) : ServiceManager { + /** + * 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 + */ + protected actual inline fun <reified RET> bind( + noinline function: T.(Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Jooby integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR, reified RET> bind( + noinline function: T.(PAR, Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Jooby integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Jooby integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Jooby integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Jooby integration.") + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + throw IllegalStateException("This class is for Jooby integration.") + } + + /** + * Applies all defined routes to the given server. + * @param k a server + */ + actual fun applyRoutes(k: KVServer) { + throw IllegalStateException("This class is for Jooby integration.") + } +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVController.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVController.kt new file mode 100644 index 00000000..128933f2 --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVController.kt @@ -0,0 +1,60 @@ +/* + * 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.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import javax.servlet.http.HttpServletRequest +import javax.servlet.http.HttpServletResponse + +@Controller +open class KVController { + + @Autowired + lateinit var kvServer: KVServer + + @RequestMapping( + "/kv/**", + method = [RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS] + ) + open fun kVMapping(req: HttpServletRequest, res: HttpServletResponse) { + val method = req.method + val routeUrl = req.requestURI + val route = kvServer.services.map { + when (method) { + "POST" -> it.postRequests[routeUrl] + "PUT" -> it.putRequests[routeUrl] + "DELETE" -> it.deleteRequests[routeUrl] + "OPTIONS" -> it.optionsRequests[routeUrl] + else -> null + } + }.find { it != null } + if (route != null) { + route.invoke(req, res) + } else { + res.status = HttpServletResponse.SC_NOT_FOUND + } + } + +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt new file mode 100644 index 00000000..730288a8 --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt @@ -0,0 +1,76 @@ +/* + * 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.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import org.pac4j.core.context.J2EContext +import org.pac4j.core.context.session.J2ESessionStore +import org.pac4j.core.profile.CommonProfile +import org.pac4j.core.profile.ProfileManager +import org.springframework.web.context.request.RequestContextHolder +import org.springframework.web.context.request.ServletRequestAttributes +import javax.servlet.http.HttpServletRequest +import kotlinx.coroutines.async as coroutinesAsync + +/** + * A Spring boot based server. + */ +actual open class KVServer(val services: List<SpringServiceManager<*>>) + +/** + * A server request. + */ +actual typealias Request = HttpServletRequest + +/** + * A user profile. + */ +actual typealias Profile = CommonProfile + +/** + * A helper extension function for asynchronous processing. + */ +fun <RESP> async(block: () -> RESP): Deferred<RESP> = + GlobalScope.coroutinesAsync(Dispatchers.Unconfined) { + block() + } + +/** + * A helper extension function for asynchronous processing with user profile. + */ +fun <RESP> asyncAuth(block: (Profile) -> RESP): Deferred<RESP> { + val profile = try { + val requestAttributes = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes) + val req = requestAttributes.request + val resp = requestAttributes.response + ProfileManager<CommonProfile>(J2EContext(req, resp, J2ESessionStore())).get(true).get() + } catch (e: Exception) { + null + } + return profile?.let { + GlobalScope.coroutinesAsync(Dispatchers.Unconfined) { + block(it) + } + } ?: throw IllegalStateException("Profile not set!") +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt new file mode 100644 index 00000000..9d80beb0 --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt @@ -0,0 +1,31 @@ +/* + * 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.springframework.web.servlet.config.annotation.InterceptorRegistration + +fun InterceptorRegistration.addPathPatternsFromServices(services: List<SpringServiceManager<*>>) { + val paths = services.flatMap { + it.postRequests.keys + it.putRequests.keys + it.optionsRequests.keys + it.optionsRequests.keys + } + this.addPathPatterns(paths) +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringContext.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringContext.kt new file mode 100644 index 00000000..6655141c --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringContext.kt @@ -0,0 +1,63 @@ +/* + * 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.springframework.beans.BeansException +import org.springframework.context.ApplicationContext +import org.springframework.context.ApplicationContextAware +import org.springframework.stereotype.Component + +@Component +class SpringContext : ApplicationContextAware { + + @Throws(BeansException::class) + override fun setApplicationContext(applicationContext: ApplicationContext) { + CONTEXT = applicationContext + } + + companion object { + + private var CONTEXT: ApplicationContext? = null + + /** + * Get a Spring bean by type. + */ + fun <T> getBean(beanClass: Class<T>): T { + return CONTEXT!!.getBean(beanClass) + } + + /** + * Get a Spring bean by name. + */ + fun getBean(beanName: String): Any { + return CONTEXT!!.getBean(beanName) + } + + /** + * Get a Spring bean by name and type. + */ + fun <T> getBean(beanName: String, beanClass: Class<T>): T { + return CONTEXT!!.getBean(beanName, beanClass) + } + } + +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt new file mode 100644 index 00000000..1baa856e --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt @@ -0,0 +1,396 @@ +/* + * 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 kotlinx.coroutines.Deferred +import kotlinx.coroutines.runBlocking +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import java.text.SimpleDateFormat +import javax.servlet.http.HttpServletResponse +import kotlin.reflect.KClass + +/** + * Multiplatform service manager for Spring Boot. + */ +actual open class SpringServiceManager<T : Any> actual constructor(val serviceClass: KClass<T>) : ServiceManager { + + companion object { + val LOG: Logger = LoggerFactory.getLogger(JoobyServiceManager::class.java.name) + } + + val postRequests: MutableMap<String, (Request, HttpServletResponse) -> Unit> = mutableMapOf() + val putRequests: MutableMap<String, (Request, HttpServletResponse) -> Unit> = mutableMapOf() + val deleteRequests: MutableMap<String, (Request, HttpServletResponse) -> Unit> = mutableMapOf() + val optionsRequests: MutableMap<String, (Request, HttpServletResponse) -> Unit> = mutableMapOf() + + val mapper = jacksonObjectMapper().apply { + dateFormat = SimpleDateFormat("YYYY-MM-DD HH:mm:ss") + } + 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: T.() -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { req, res -> + val service = SpringContext.getBean(serviceClass.java) + val jsonRpcRequest = mapper.readValue(req.inputStream, JsonRpcRequest::class.java) + try { + val result = runBlocking { function.invoke(service).await() } + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.writeJSON( + mapper.writeValueAsString( + 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: T.(PAR) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { req, res -> + val service = SpringContext.getBean(serviceClass.java) + val jsonRpcRequest = mapper.readValue(req.inputStream, JsonRpcRequest::class.java) + if (jsonRpcRequest.params.size == 1) { + val param = getParameter<PAR>(jsonRpcRequest.params[0]) + try { + val result = runBlocking { function.invoke(service, param).await() } + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + ) + } + } else { + res.writeJSON( + mapper.writeValueAsString( + 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: T.(PAR1, PAR2) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { req, res -> + val service = SpringContext.getBean(serviceClass.java) + val jsonRpcRequest = mapper.readValue(req.inputStream, JsonRpcRequest::class.java) + if (jsonRpcRequest.params.size == 2) { + val param1 = getParameter<PAR1>(jsonRpcRequest.params[0]) + val param2 = getParameter<PAR2>(jsonRpcRequest.params[1]) + try { + val result = runBlocking { function.invoke(service, param1, param2).await() } + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + ) + } + } else { + res.writeJSON( + mapper.writeValueAsString( + 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: T.(PAR1, PAR2, PAR3) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { req, res -> + val service = SpringContext.getBean(serviceClass.java) + val jsonRpcRequest = mapper.readValue(req.inputStream, JsonRpcRequest::class.java) + @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 = runBlocking { function.invoke(service, param1, param2, param3).await() } + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + ) + } + } else { + res.writeJSON( + mapper.writeValueAsString( + 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: T.(PAR1, PAR2, PAR3, PAR4) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { req, res -> + val service = SpringContext.getBean(serviceClass.java) + val jsonRpcRequest = mapper.readValue(req.inputStream, JsonRpcRequest::class.java) + @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 = + runBlocking { function.invoke(service, param1, param2, param3, param4).await() } + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + ) + } + } else { + res.writeJSON( + mapper.writeValueAsString( + 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: T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + addRoute(method, "/kv/$routeDef") { req, res -> + val service = SpringContext.getBean(serviceClass.java) + val jsonRpcRequest = mapper.readValue(req.inputStream, JsonRpcRequest::class.java) + @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 = + runBlocking { + function.invoke(service, param1, param2, param3, param4, param5).await() + } + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + result = mapper.writeValueAsString(result) + ) + ) + ) + } catch (e: Exception) { + LOG.error(e.message, e) + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = e.message ?: "Error" + ) + ) + ) + } + } else { + res.writeJSON( + mapper.writeValueAsString( + JsonRpcResponse( + id = jsonRpcRequest.id, + error = "Invalid parameters" + ) + ) + ) + } + } + } + + fun addRoute( + method: RpcHttpMethod, + path: String, + handler: (Request, HttpServletResponse) -> Unit + ) { + when (method) { + RpcHttpMethod.POST -> postRequests[path] = handler + RpcHttpMethod.PUT -> putRequests[path] = handler + RpcHttpMethod.DELETE -> deleteRequests[path] = handler + RpcHttpMethod.OPTIONS -> optionsRequests[path] = handler + } + } + + @Suppress("TooGenericExceptionCaught") + 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 + } +} + +fun HttpServletResponse.writeJSON(json: String) { + val out = this.outputStream + this.contentType = "application/json" + this.characterEncoding = "UTF-8" + out.write(json.toByteArray()) + out.flush() +} diff --git a/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/types/Date.kt b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/types/Date.kt new file mode 100644 index 00000000..32c8923e --- /dev/null +++ b/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/types/Date.kt @@ -0,0 +1,46 @@ +/* + * 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 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 +) diff --git a/settings.gradle b/settings.gradle index bfde8029..a8cb0e9c 100644 --- a/settings.gradle +++ b/settings.gradle @@ -10,4 +10,5 @@ include 'kvision-modules:kvision-base', 'kvision-modules:kvision-upload', 'kvision-modules:kvision-handlebars', 'kvision-modules:kvision-i18n', - 'kvision-modules:kvision-server-jooby' + 'kvision-modules:kvision-server-jooby', + 'kvision-modules:kvision-server-spring-boot' diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/JoobyRemoteAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/JoobyRemoteAgent.kt new file mode 100644 index 00000000..b4cc6c21 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/JoobyRemoteAgent.kt @@ -0,0 +1,369 @@ +/* + * 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.Deferred +import kotlinx.coroutines.asDeferred +import kotlinx.serialization.list +import kotlinx.serialization.serializer +import pl.treksoft.kvision.utils.JSON +import kotlin.js.js +import kotlin.reflect.KClass +import kotlin.js.JSON as NativeJSON + +/** + * Client side agent for JSON-RPC remote calls with Jooby. + */ +@Suppress("LargeClass", "TooManyFunctions") +open class JoobyRemoteAgent<T : Any>(val serviceManager: JoobyServiceManager<T>) : RemoteAgent { + + val callAgent = CallAgent() + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified RET : Any, T> call(noinline function: T.(Request?) -> Deferred<RET>): Deferred<RET> { + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, method = method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified RET : Any, T> call( + noinline function: T.(Request?) -> Deferred<List<RET>> + ): Deferred<List<RET>> { + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, method = method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR, reified RET : Any, T> call( + noinline function: T.(PAR, Request?) -> Deferred<RET>, p: PAR + ): Deferred<RET> { + val data = serialize(p) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR, reified RET : Any, T> call( + noinline function: T.(PAR, Request?) -> Deferred<List<RET>>, p: PAR + ): Deferred<List<RET>> { + val data = serialize(p) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, p1: PAR1, p2: PAR2 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred<List<RET>>, p1: PAR1, p2: PAR2 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, p1: PAR1, p2: PAR2, p3: PAR3 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<List<RET>>, p1: PAR1, p2: PAR2, p3: PAR3 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, p1: PAR1, p2: PAR2, p3: PAR3, p4: PAR4 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<List<RET>>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, + reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val data5 = serialize(p5) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, + reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<List<RET>>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val data5 = serialize(p5) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + + /** + * @suppress + * Internal function + */ + inline fun <reified PAR> serialize(value: PAR): String? { + return value?.let { + @Suppress("UNCHECKED_CAST") + trySerialize((PAR::class as KClass<Any>), it as Any) + } + } + +} diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt index c6487494..c9d8ba25 100644 --- a/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt +++ b/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt @@ -24,9 +24,10 @@ package pl.treksoft.kvision.remote import kotlinx.coroutines.Deferred /** - * Multiplatform service manager. + * Multiplatform service manager for Jooby. */ -actual open class ServiceManager<out T> actual constructor(service: T) { +actual open class JoobyServiceManager<T : Any> actual constructor(service: T) : ServiceManager { + protected val calls: MutableMap<String, Pair<String, RpcHttpMethod>> = mutableMapOf() var counter: Int = 0 @@ -35,14 +36,13 @@ actual open class ServiceManager<out T> actual constructor(service: T) { * @param function a function of the receiver * @param route a route * @param method a HTTP method - * @param prefix an URL address prefix */ protected actual inline fun <reified RET> bind( noinline function: T.(Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String + route: String?, method: RpcHttpMethod ) { val routeDef = route ?: "route${this::class.simpleName}${counter++}" - calls[function.toString()] = Pair("$prefix$routeDef", method) + calls[function.toString()] = Pair("/kv/$routeDef", method) } /** @@ -50,14 +50,13 @@ actual open class ServiceManager<out T> actual constructor(service: T) { * @param function a function of the receiver * @param route a route * @param method a HTTP method - * @param prefix an URL address prefix */ protected actual inline fun <reified PAR, reified RET> bind( noinline function: T.(PAR, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String + route: String?, method: RpcHttpMethod ) { val routeDef = route ?: "route${this::class.simpleName}${counter++}" - calls[function.toString()] = Pair("$prefix$routeDef", method) + calls[function.toString()] = Pair("/kv/$routeDef", method) } /** @@ -65,14 +64,13 @@ actual open class ServiceManager<out T> actual constructor(service: T) { * @param function a function of the receiver * @param route a route * @param method a HTTP method - * @param prefix an URL address prefix */ protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String + route: String?, method: RpcHttpMethod ) { val routeDef = route ?: "route${this::class.simpleName}${counter++}" - calls[function.toString()] = Pair("$prefix$routeDef", method) + calls[function.toString()] = Pair("/kv/$routeDef", method) } /** @@ -80,14 +78,13 @@ actual open class ServiceManager<out T> actual constructor(service: T) { * @param function a function of the receiver * @param route a route * @param method a HTTP method - * @param prefix an URL address prefix */ protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String + route: String?, method: RpcHttpMethod ) { val routeDef = route ?: "route${this::class.simpleName}${counter++}" - calls[function.toString()] = Pair("$prefix$routeDef", method) + calls[function.toString()] = Pair("/kv/$routeDef", method) } /** @@ -95,14 +92,13 @@ actual open class ServiceManager<out T> actual constructor(service: T) { * @param function a function of the receiver * @param route a route * @param method a HTTP method - * @param prefix an URL address prefix */ protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, - route: String?, method: RpcHttpMethod, prefix: String + route: String?, method: RpcHttpMethod ) { val routeDef = route ?: "route${this::class.simpleName}${counter++}" - calls[function.toString()] = Pair("$prefix$routeDef", method) + calls[function.toString()] = Pair("/kv/$routeDef", method) } /** @@ -110,17 +106,15 @@ actual open class ServiceManager<out T> actual constructor(service: T) { * @param function a function of the receiver * @param route a route * @param method a HTTP method - * @param prefix an URL address prefix */ protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, reified RET> bind( noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, route: String?, - method: RpcHttpMethod, - prefix: String + method: RpcHttpMethod ) { val routeDef = route ?: "route${this::class.simpleName}${counter++}" - calls[function.toString()] = Pair("$prefix$routeDef", method) + calls[function.toString()] = Pair("/kv/$routeDef", method) } /** @@ -133,5 +127,5 @@ actual open class ServiceManager<out T> actual constructor(service: T) { /** * Returns the map of defined paths. */ - actual fun getCalls(): Map<String, Pair<String, RpcHttpMethod>> = calls + override fun getCalls(): Map<String, Pair<String, RpcHttpMethod>> = calls } diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt index b757398a..b1ee4fde 100644 --- a/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt +++ b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt @@ -21,8 +21,6 @@ */ package pl.treksoft.kvision.remote -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.asDeferred import kotlinx.serialization.KSerializer import kotlinx.serialization.internal.BooleanSerializer import kotlinx.serialization.internal.ByteSerializer @@ -39,350 +37,16 @@ import pl.treksoft.kvision.types.DateSerializer import pl.treksoft.kvision.types.toStringF import pl.treksoft.kvision.utils.JSON import kotlin.js.Date -import kotlin.js.asDynamic -import kotlin.js.js import kotlin.reflect.KClass -import kotlin.js.JSON as NativeJSON internal class NotStandardTypeException(type: String) : Exception("Not a standard type: $type!") internal class NotEnumTypeException : Exception("Not the Enum type!") /** - * Client side agent for JSON-RPC remote calls. + * Interface for client side agent for JSON-RPC remote calls. */ -@Suppress("LargeClass", "TooManyFunctions") -open class RemoteAgent<out T>(val serviceManager: ServiceManager<T>) { - - val callAgent = CallAgent() - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified RET : Any, T> call(noinline function: T.(Request?) -> Deferred<RET>): Deferred<RET> { - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, method = method).then { - try { - @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnum(RET::class as KClass<Any>, it) as RET - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified RET : Any, T> call( - noinline function: T.(Request?) -> Deferred<List<RET>> - ): Deferred<List<RET>> { - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, method = method).then { - try { - deserializeList<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR, reified RET : Any, T> call( - noinline function: T.(PAR, Request?) -> Deferred<RET>, p: PAR - ): Deferred<RET> { - val data = serialize(p) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data), method).then { - try { - @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnum(RET::class as KClass<Any>, it) as RET - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR, reified RET : Any, T> call( - noinline function: T.(PAR, Request?) -> Deferred<List<RET>>, p: PAR - ): Deferred<List<RET>> { - val data = serialize(p) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data), method).then { - try { - deserializeList<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, Request?) -> Deferred<RET>, p1: PAR1, p2: PAR2 - ): Deferred<RET> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { - try { - @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnum(RET::class as KClass<Any>, it) as RET - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, Request?) -> Deferred<List<RET>>, p1: PAR1, p2: PAR2 - ): Deferred<List<RET>> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { - try { - deserializeList<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<RET>, p1: PAR1, p2: PAR2, p3: PAR3 - ): Deferred<RET> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val data3 = serialize(p3) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { - try { - @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnum(RET::class as KClass<Any>, it) as RET - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred<List<RET>>, p1: PAR1, p2: PAR2, p3: PAR3 - ): Deferred<List<RET>> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val data3 = serialize(p3) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { - try { - deserializeList<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<RET>, p1: PAR1, p2: PAR2, p3: PAR3, p4: PAR4 - ): Deferred<RET> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val data3 = serialize(p3) - val data4 = serialize(p4) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { - try { - @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnum(RET::class as KClass<Any>, it) as RET - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred<List<RET>>, - p1: PAR1, - p2: PAR2, - p3: PAR3, - p4: PAR4 - ): Deferred<List<RET>> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val data3 = serialize(p3) - val data4 = serialize(p4) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { - try { - deserializeList<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - @Suppress("LongParameterList") - inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, - reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<RET>, - p1: PAR1, - p2: PAR2, - p3: PAR3, - p4: PAR4, - p5: PAR5 - ): Deferred<RET> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val data3 = serialize(p3) - val data4 = serialize(p4) - val data5 = serialize(p5) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { - try { - @Suppress("UNCHECKED_CAST") - deserialize<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnum(RET::class as KClass<Any>, it) as RET - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer(), it) - } - } - }.asDeferred() - } - - /** - * Executes defined call to a remote web service. - */ - @Suppress("LongParameterList") - inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, - reified RET : Any, T> call( - noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred<List<RET>>, - p1: PAR1, - p2: PAR2, - p3: PAR3, - p4: PAR4, - p5: PAR5 - ): Deferred<List<RET>> { - val data1 = serialize(p1) - val data2 = serialize(p2) - val data3 = serialize(p3) - val data4 = serialize(p4) - val data5 = serialize(p5) - val (url, method) = - serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") - return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { - try { - deserializeList<RET>(it, RET::class.js.name) - } catch (t: NotStandardTypeException) { - try { - @Suppress("UNCHECKED_CAST") - tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> - } catch (t: NotEnumTypeException) { - JSON.nonstrict.parse(RET::class.serializer().list, it) - } - } - }.asDeferred() - } - - - /** - * @suppress - * Internal function - */ - inline fun <reified PAR> serialize(value: PAR): String? { - return value?.let { - @Suppress("UNCHECKED_CAST") - trySerialize((PAR::class as KClass<Any>), it as Any) - } - } +interface RemoteAgent { /** * @suppress diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/SpringRemoteAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/SpringRemoteAgent.kt new file mode 100644 index 00000000..f1f3b473 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/SpringRemoteAgent.kt @@ -0,0 +1,369 @@ +/* + * 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.Deferred +import kotlinx.coroutines.asDeferred +import kotlinx.serialization.list +import kotlinx.serialization.serializer +import pl.treksoft.kvision.utils.JSON +import kotlin.js.js +import kotlin.reflect.KClass +import kotlin.js.JSON as NativeJSON + +/** + * Client side agent for JSON-RPC remote calls with Spring Boot. + */ +@Suppress("LargeClass", "TooManyFunctions") +open class SpringRemoteAgent<T : Any>(val serviceManager: SpringServiceManager<T>) : RemoteAgent { + + val callAgent = CallAgent() + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified RET : Any, T> call(noinline function: T.() -> Deferred<RET>): Deferred<RET> { + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, method = method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified RET : Any, T> call( + noinline function: T.() -> Deferred<List<RET>> + ): Deferred<List<RET>> { + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, method = method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR, reified RET : Any, T> call( + noinline function: T.(PAR) -> Deferred<RET>, p: PAR + ): Deferred<RET> { + val data = serialize(p) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR, reified RET : Any, T> call( + noinline function: T.(PAR) -> Deferred<List<RET>>, p: PAR + ): Deferred<List<RET>> { + val data = serialize(p) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2) -> Deferred<RET>, p1: PAR1, p2: PAR2 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2) -> Deferred<List<RET>>, p1: PAR1, p2: PAR2 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3) -> Deferred<RET>, p1: PAR1, p2: PAR2, p3: PAR3 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3) -> Deferred<List<RET>>, p1: PAR1, p2: PAR2, p3: PAR3 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4) -> Deferred<RET>, p1: PAR1, p2: PAR2, p3: PAR3, p4: PAR4 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4) -> Deferred<List<RET>>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, + reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> Deferred<RET>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5 + ): Deferred<RET> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val data5 = serialize(p5) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnum(RET::class as KClass<Any>, it) as RET + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer(), it) + } + } + }.asDeferred() + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified PAR5, + reified RET : Any, T> call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> Deferred<List<RET>>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5 + ): Deferred<List<RET>> { + val data1 = serialize(p1) + val data2 = serialize(p2) + val data3 = serialize(p3) + val data4 = serialize(p4) + val data5 = serialize(p5) + val (url, method) = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return callAgent.jsonRpcCall(url, listOf(data1, data2, data3, data4, data5), method).then { + try { + deserializeList<RET>(it, RET::class.js.name) + } catch (t: NotStandardTypeException) { + try { + @Suppress("UNCHECKED_CAST") + tryDeserializeEnumList(RET::class as KClass<Any>, it) as List<RET> + } catch (t: NotEnumTypeException) { + JSON.nonstrict.parse(RET::class.serializer().list, it) + } + } + }.asDeferred() + } + + + /** + * @suppress + * Internal function + */ + inline fun <reified PAR> serialize(value: PAR): String? { + return value?.let { + @Suppress("UNCHECKED_CAST") + trySerialize((PAR::class as KClass<Any>), it as Any) + } + } + +} diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt b/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt new file mode 100644 index 00000000..6b26da8e --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt @@ -0,0 +1,125 @@ +/* + * 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.Deferred +import kotlin.reflect.KClass + +/** + * Multiplatform service manager for Spring Boot. + */ +actual open class SpringServiceManager<T : Any> actual constructor(serviceClass: KClass<T>) : ServiceManager { + + protected val calls: MutableMap<String, Pair<String, RpcHttpMethod>> = mutableMapOf() + 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 + */ + protected actual inline fun <reified RET> bind( + noinline function: T.() -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString()] = Pair("/kv/$routeDef", method) + } + + /** + * 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 + */ + protected actual inline fun <reified PAR, reified RET> bind( + noinline function: T.(PAR) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString()] = Pair("/kv/$routeDef", method) + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified RET> bind( + noinline function: T.(PAR1, PAR2) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString()] = Pair("/kv/$routeDef", method) + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString()] = Pair("/kv/$routeDef", method) + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, reified PAR4, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4) -> Deferred<RET>, + route: String?, method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString()] = Pair("/kv/$routeDef", method) + } + + /** + * 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 + */ + protected actual inline fun <reified PAR1, reified PAR2, reified PAR3, + reified PAR4, reified PAR5, reified RET> bind( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5) -> Deferred<RET>, + route: String?, + method: RpcHttpMethod + ) { + val routeDef = route ?: "route${this::class.simpleName}${counter++}" + calls[function.toString()] = Pair("/kv/$routeDef", method) + } + + /** + * Returns the map of defined paths. + */ + override fun getCalls(): Map<String, Pair<String, RpcHttpMethod>> = calls +} |