GatewayClient.kt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package co.id.datacomsolusindo.ipphonebridge
  2. import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
  3. import org.apache.commons.io.IOUtils
  4. import org.springframework.core.io.ByteArrayResource
  5. import org.springframework.core.io.Resource
  6. import org.springframework.http.HttpEntity
  7. import org.springframework.http.HttpHeaders
  8. import org.springframework.http.HttpMethod
  9. import org.springframework.http.HttpStatus
  10. import org.springframework.messaging.converter.MappingJackson2MessageConverter
  11. import org.springframework.messaging.simp.SimpMessagingTemplate
  12. import org.springframework.messaging.simp.stomp.StompCommand
  13. import org.springframework.messaging.simp.stomp.StompHeaders
  14. import org.springframework.messaging.simp.stomp.StompSession
  15. import org.springframework.messaging.simp.stomp.StompSessionHandler
  16. import org.springframework.util.LinkedMultiValueMap
  17. import org.springframework.util.MultiValueMap
  18. import org.springframework.web.client.HttpStatusCodeException
  19. import org.springframework.web.client.RestTemplate
  20. import org.springframework.web.socket.client.standard.StandardWebSocketClient
  21. import org.springframework.web.socket.messaging.WebSocketStompClient
  22. import java.io.Serializable
  23. import java.lang.reflect.Type
  24. import java.net.URI
  25. import java.nio.charset.Charset
  26. import java.util.*
  27. import java.util.concurrent.ConcurrentHashMap
  28. import java.util.concurrent.ConcurrentMap
  29. class GatewayClient(
  30. val socketHost: String,
  31. val clientName: String,
  32. val currentLocalPort: Int,
  33. val socketPort: Int,
  34. val srvTemplate: SimpMessagingTemplate
  35. ) {
  36. enum class State { INITIALIZED, CONNECTING, FAILED, CONNECT }
  37. var state = State.INITIALIZED
  38. var session: StompSession? = null
  39. fun connect() {
  40. try {
  41. state = State.CONNECTING
  42. val client = StandardWebSocketClient()
  43. val stompClient = WebSocketStompClient(client)
  44. stompClient.messageConverter = MappingJackson2MessageConverter()
  45. val sessionHandler =
  46. BridgeStompSessionHandler(srvTemplate)
  47. AppLog.write(this.javaClass).info("Try connect to : ws://$socketHost:$socketPort/_websocket")
  48. val cn = stompClient.connect("ws://$socketHost:$socketPort/_websocket", sessionHandler)
  49. cn.addCallback({ s ->
  50. session = s
  51. if (s != null && s.isConnected) {
  52. AppLog.write(this.javaClass).info("Socket is connected.")
  53. state = State.CONNECT
  54. }
  55. }, { e ->
  56. AppLog.write(this.javaClass).info("Can't connect to socket server.")
  57. AppLog.write(this.javaClass).error(e.message, e)
  58. state = State.FAILED
  59. })
  60. session = sessionHandler.session
  61. } catch (e: Exception) {
  62. AppLog.write(this.javaClass)
  63. .info("Can't connect to socket server, check your configuration and log. retry in 5 second")
  64. AppLog.write(this.javaClass).error(e.message, e)
  65. state = State.FAILED
  66. }
  67. }
  68. }
  69. class BridgeStompSessionHandler(val srvTemplate: SimpMessagingTemplate) : StompSessionHandler {
  70. var session: StompSession? = null
  71. // val partialDataMap: ConcurrentMap<String, MutableList<PartialData>> = ConcurrentHashMap()
  72. // val partialDataMap: ConcurrentMap<String, ConcurrentMap<Int, PartialData>> = ConcurrentHashMap()
  73. override fun handleException(
  74. session: StompSession,
  75. command: StompCommand?,
  76. headers: StompHeaders,
  77. btar: ByteArray,
  78. error: Throwable
  79. ) {
  80. AppLog.write(this.javaClass).info("Socket Handle Error")
  81. AppLog.write(this.javaClass).error("Socket Handle Error", error)
  82. }
  83. override fun handleTransportError(session: StompSession, error: Throwable) {
  84. AppLog.write(this.javaClass).info("Socket Transport Error")
  85. AppLog.write(this.javaClass).error("Socket Transport Error", error)
  86. }
  87. override fun getPayloadType(headers: StompHeaders): Type {
  88. return Any::class.java
  89. }
  90. override fun afterConnected(ss: StompSession, sh: StompHeaders) {
  91. AppLog.write(this.javaClass).info("Connected to gateway socket server")
  92. // ss.subscribe("/topic/partial/$clientName", this)
  93. // ss.subscribe("/topic/healthCheck", this)
  94. this.session = ss
  95. }
  96. override fun handleFrame(stompHeaders: StompHeaders, payload: Any?) {
  97. // "/topic/incoming/clnum"
  98. if (payload != null) {
  99. val reqId = Singletons.requestInstance.entries.map { it.key }
  100. .firstOrNull { stompHeaders.destination?.endsWith(it) ?: false } ?: ""
  101. val clientDest =
  102. ClientHolder.get().map { it.key }.firstOrNull { stompHeaders.destination?.endsWith(it) ?: false } ?: ""
  103. //
  104. when (stompHeaders.destination) {
  105. "/topic/partial/$clientDest" -> {
  106. srvTemplate.convertAndSend(
  107. "/topic/partial/$clientDest",
  108. payload
  109. )
  110. }
  111. "/topic/response/$reqId" -> {
  112. SocketChecker().collectChunk(payload as SocketChunkData,reqId)
  113. }
  114. }
  115. }
  116. // when (stompHeaders.destination) {
  117. // "/topic/healthCheck" -> {
  118. // if ((1..100).random() == 5) {
  119. // val msgObj = payload as LinkedHashMap<*, *>
  120. // AppLog.write(javaClass).info("Socket Health Check " + msgObj["Hi"])
  121. // }
  122. // }
  123. // "/topic/request/$clientName" -> {
  124. // //process
  125. // this.session!!.send("/app/confirm/req", "OK")
  126. // }
  127. //
  128. // "/topic/partial/$clientName" -> {
  129. // val msgObj = payload as LinkedHashMap<*, *>
  130. // val partData = PartialData(
  131. // msgObj["id"] as String,
  132. // msgObj["total"] as Int,
  133. // msgObj["idx"] as Int,
  134. // msgObj["data"] as String,
  135. // msgObj["startTime"] as Long
  136. // )
  137. //
  138. // val pt = partialDataMap.getOrPut(payload["id"] as String) {
  139. // ConcurrentHashMap()
  140. // }
  141. // pt.getOrPut(partData.idx){partData}
  142. // val listChunk = pt.entries.sortedBy { it.key }.map { it.value }
  143. // if (listChunk.isNotEmpty() && listChunk.size == listChunk[0].total) {
  144. // val rbJs = listChunk.joinToString("") { it.data }
  145. //
  146. // val mapper = jacksonObjectMapper()
  147. // val rb = mapper.readValue(rbJs, RequestBuilder::class.java)
  148. // requestBuilderProcessor(rb, listChunk[0].startTime)
  149. // }
  150. //
  151. // }
  152. // else -> {
  153. // AppLog.write(this.javaClass)
  154. // .info("unknown message from ${stompHeaders.destination} with message $payload")
  155. // }
  156. //
  157. // }
  158. }
  159. // fun requestBuilderProcessor(rb: RequestBuilder, startTime: Long) {
  160. // var intStartTime = startTime
  161. // val headers: MultiValueMap<String, String> = LinkedMultiValueMap<String, String>()
  162. // rb.headers.entries.forEach { headers[it.key] = mutableListOf(it.value) }
  163. // var url = "http://localhost:" + currentLocalPort + rb.path
  164. // AppLog.write(this.javaClass).info("-----------request builder -----------")
  165. // AppLog.write(this.javaClass).info(rb.body)
  166. // AppLog.write(this.javaClass).info(rb.headers)
  167. // AppLog.write(this.javaClass).info(rb.parts)
  168. // AppLog.write(this.javaClass).info(rb.queryString)
  169. // AppLog.write(this.javaClass).info("-----------end builder -----------")
  170. //
  171. // val queryString = rb.queryString
  172. //
  173. // if (queryString != null) {
  174. // url = "$url?$queryString"
  175. // }
  176. //
  177. // val urlSend = URI(url)
  178. // AppLog.write(this.javaClass).info("socket -> url to access $url")
  179. //
  180. // val httpEnt = rb.parts?.let {
  181. // val bodyPart: MultiValueMap<String, Any> = LinkedMultiValueMap()
  182. // it.forEach { fp ->
  183. // bodyPart.add(
  184. // fp.name,
  185. // FileNameAwareByteArrayResource(fp.fileName, Base64.getDecoder().decode(fp.data), null)
  186. // )
  187. // }
  188. // HttpEntity(bodyPart, headers)
  189. // } ?: HttpEntity(rb.body?.replace("\r\n", "\n")?.replace("\r", "\n")?.replace("\n", "\r\n"), headers)
  190. //
  191. // val d1 = (System.nanoTime() - intStartTime).toDouble() / 1000000 //divide by 1000000 to get milliseconds.
  192. //
  193. // AppLog.write(this.javaClass).info("Socket prc preparation. Time: $d1, ID: ${rb.id}")
  194. // intStartTime = System.nanoTime()
  195. //
  196. // var hd: HttpHeaders? = null
  197. // var stat: Int
  198. // var bdz: ByteArray?
  199. //
  200. // try {
  201. // val response = restTemplate.exchange(urlSend, rb.method, httpEnt, Resource::class.java)
  202. // bdz = if (response.body != null) {
  203. // IOUtils.toByteArray(response.body!!.inputStream)
  204. // } else {
  205. // ByteArray(0)
  206. // }
  207. // hd = response.headers
  208. // stat = response.statusCode.value()
  209. // } catch (httpError: HttpStatusCodeException) {
  210. // AppLog.write(this.javaClass).info("http error + ${httpError.message}")
  211. // AppLog.write(this.javaClass).error("http error", httpError)
  212. // bdz = httpError.responseBodyAsByteArray
  213. // hd = httpError.responseHeaders
  214. // stat = httpError.statusCode.value()
  215. //
  216. // }
  217. // catch (ex: Exception) {
  218. // AppLog.write(this.javaClass).info("request error")
  219. // AppLog.write(this.javaClass).error("request error", ex)
  220. // stat = HttpStatus.BAD_REQUEST.ordinal
  221. // bdz = "unknown error".toByteArray(Charset.defaultCharset())
  222. // }
  223. //
  224. // val d2 = (System.nanoTime() - intStartTime).toDouble() / 1000000 //divide by 1000000 to get milliseconds.
  225. // AppLog.write(this.javaClass).info("Socket loop internal prc. Time: $d2, ID: ${rb.id}")
  226. // intStartTime = System.nanoTime()
  227. //
  228. // this.session?.let {
  229. // val chunkSize = 2000
  230. // if (bdz != null && bdz.size > chunkSize) {
  231. // val chunk = bdz.toList().chunked(chunkSize).map { bt -> bt.toByteArray() }
  232. // chunk.forEachIndexed { idx, bt ->
  233. // if (idx < chunk.size - 1) {
  234. // it.send("/app/response/${rb.id}", SocketChunkData(bt, null, stat, idx, chunk.size))
  235. // } else {
  236. // it.send("/app/response/${rb.id}", SocketChunkData(bt, hd, stat, idx, chunk.size))//send
  237. // }
  238. // }
  239. // } else {
  240. // //send
  241. // it.send("/app/response/${rb.id}", SocketChunkData(bdz, hd, stat, 1, 1))
  242. // }
  243. // }
  244. // val d3 = (System.nanoTime() - intStartTime).toDouble() / 1000000 //divide by 1000000 to get milliseconds.
  245. // AppLog.write(this.javaClass).info("Socket send response. Time: $d3, ID: ${rb.id}")
  246. // val duration = (System.nanoTime() - startTime).toDouble() / 1000000 //divide by 1000000 to get milliseconds.
  247. // AppLog.write(this.javaClass).info("Bridge total process Success. Time: $duration, ID: ${rb.id}, URL: $urlSend")
  248. //
  249. // }
  250. //
  251. // class FileNameAwareByteArrayResource(private val fName: String, byteArray: ByteArray, description: String?) :
  252. // ByteArrayResource(byteArray, description) {
  253. // override fun getFilename() = fName
  254. // }
  255. //
  256. // class PartialData(val id: String, val total: Int, val idx: Int, val data: String, val startTime: Long)
  257. //
  258. // class RequestBuilder(
  259. // val id: String,
  260. // val path: String,
  261. // var method: HttpMethod,
  262. // var headers: MutableMap<String, String>
  263. // ) : Serializable {
  264. // var body: String? = null
  265. // var queryString: String? = null
  266. // var parts: MutableList<FilePart>? = null
  267. // }
  268. //
  269. // class FilePart(val name: String, val fileName: String, val data: String)
  270. //
  271. // class SocketChunkData(
  272. // val body: ByteArray?,
  273. // val header: HttpHeaders?,
  274. // val status: Int,
  275. // val part: Int,
  276. // val totalPart: Int
  277. // )
  278. // val messageMap: ConcurrentMap<String, MutableList<Message>> = ConcurrentHashMap()
  279. }