77 lines
2.9 KiB
Kotlin
77 lines
2.9 KiB
Kotlin
package net.ipksindia
|
|
import kotlinx.serialization.encodeToString
|
|
import kotlinx.serialization.json.Json
|
|
import net.ipksindia.config.AppConfig
|
|
import net.ipksindia.model.NeftTransaction
|
|
import net.ipksindia.model.TransferTransaction
|
|
import net.ipksindia.response.TransactionFailureResponse
|
|
import okhttp3.MediaType.Companion.toMediaType
|
|
import okhttp3.OkHttpClient
|
|
import okhttp3.Request
|
|
import okhttp3.RequestBody.Companion.toRequestBody
|
|
import org.json.JSONObject
|
|
import org.slf4j.LoggerFactory
|
|
import response.TransactionResponse
|
|
import response.TransactionSuccessResponse
|
|
import java.io.IOException
|
|
|
|
|
|
class TransactionExecutor {
|
|
private val logger = LoggerFactory.getLogger(TransactionExecutor::class.java)
|
|
private val transactionUrl = AppConfig.remoteServerConfig.transactionUrl
|
|
|
|
fun executePair(transactionPair: Pair<TransferTransaction, NeftTransaction>): Pair<TransactionResponse, TransactionResponse> {
|
|
|
|
val transferTransaction = transactionPair.first
|
|
val neftTransaction = transactionPair.second
|
|
logger.debug("TRF-RRN: {}, NEFT-RRN: {}", transferTransaction.rrn, neftTransaction.rrn)
|
|
|
|
val transferResponseString = execute(Json.encodeToString(transferTransaction))
|
|
val transferResponse = processResponse(transferResponseString)
|
|
|
|
val neftResponseString = execute(Json.encodeToString(neftTransaction))
|
|
val neftResponse = processResponse(neftResponseString)
|
|
return Pair(transferResponse, neftResponse)
|
|
}
|
|
|
|
private fun execute(postBody: String): String {
|
|
logger.debug("request: {}", postBody)
|
|
val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
|
|
|
val httpClient = OkHttpClient
|
|
.Builder()
|
|
.hostnameVerifier { _, _ -> true }
|
|
.build()
|
|
|
|
val request = Request
|
|
.Builder()
|
|
.url(transactionUrl)
|
|
.post(postBody.toRequestBody(jsonMediaType))
|
|
.build()
|
|
|
|
return httpClient.newCall(request).execute().use { response ->
|
|
if (!response.isSuccessful) {
|
|
throw IOException("Unexpected response: ${response.body}")
|
|
}
|
|
val responseString = response.body?.string() ?: throw IOException("no response body")
|
|
logger.debug("response: {}", responseString)
|
|
responseString
|
|
}
|
|
|
|
}
|
|
|
|
private fun processResponse(responseBody: String): TransactionResponse {
|
|
val responseObj = JSONObject(responseBody)
|
|
val status = responseObj.getString("status")
|
|
val message = responseObj.getString("message")
|
|
val error = responseObj.getInt("error")
|
|
|
|
return if (responseBody.contains("SUCCESS")) {
|
|
val queueNo = responseObj.getJSONObject("response").getString("QueueId")
|
|
TransactionSuccessResponse(status, message, queueNo, error)
|
|
} else {
|
|
TransactionFailureResponse(status, message, error)
|
|
}
|
|
}
|
|
}
|