aboutsummaryrefslogtreecommitdiff
path: root/kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote
diff options
context:
space:
mode:
authorRobert Jaros <rjaros@finn.pl>2018-10-20 03:43:02 +0200
committerRobert Jaros <rjaros@finn.pl>2018-10-20 03:43:02 +0200
commit0c9ee826d545befe2c6e1c740bd5f74ed453b899 (patch)
tree90edc46509e6a2a653e8fa8af12588f9c0a291c2 /kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote
parent295220e1b186f50d72ca9336ed031f8a370c2aa8 (diff)
downloadkvision-0c9ee826d545befe2c6e1c740bd5f74ed453b899.tar.gz
kvision-0c9ee826d545befe2c6e1c740bd5f74ed453b899.tar.bz2
kvision-0c9ee826d545befe2c6e1c740bd5f74ed453b899.zip
New kvision-server-spring-boot module with support for Spring Boot server-side integration.
Kotlin upgrade to 1.3.0-rc-190.
Diffstat (limited to 'kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote')
-rw-r--r--kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/JoobyServiceManager.kt122
-rw-r--r--kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVController.kt60
-rw-r--r--kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/KVServer.kt76
-rw-r--r--kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/Security.kt31
-rw-r--r--kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringContext.kt63
-rw-r--r--kvision-modules/kvision-server-spring-boot/src/main/kotlin/pl/treksoft/kvision/remote/SpringServiceManager.kt396
6 files changed, 748 insertions, 0 deletions
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()
+}