How to use ByteArray.encodeBase64 method of com.github.kittinunf.fuel.util.Base64 class

Best Fuel code snippet using com.github.kittinunf.fuel.util.Base64.ByteArray.encodeBase64

Kkiapay.kt

Source:Kkiapay.kt Github

copy

Full Screen

1package co.opensi.kkiapay.uikit2import android.app.Activity3import android.content.Context4import android.content.Intent5import android.graphics.Bitmap6import android.graphics.BitmapFactory7import android.util.Log8import androidx.annotation.ColorRes9import androidx.annotation.RawRes10import androidx.appcompat.app.AppCompatActivity11import androidx.core.content.ContextCompat12import co.opensi.kkiapay.Error13import co.opensi.kkiapay.MomoPay14import co.opensi.kkiapay.STATUS15import co.opensi.kkiapay.Transaction16import co.opensi.kkiapay.uikit.KKiapayApi.Companion.checkTransactionStatus17import co.opensi.kkiapay.uikit.Me.Companion.KKIAPAY_REQUEST_CODE18import co.opensi.kkiapay.uikit.Me.Companion.KKIAPAY_URL19import co.opensi.kkiapay.uikit.SandBoxKKiapayApi.Companion.sandboxCheckTransactionStatus20import com.github.kittinunf.fuel.Fuel21import com.github.kittinunf.fuel.core.FileDataPart22import com.github.kittinunf.fuel.core.HeaderValues23import com.github.kittinunf.fuel.core.Method24import com.github.kittinunf.fuel.core.Parameters25import com.github.kittinunf.fuel.core.requests.upload26import com.github.kittinunf.fuel.util.FuelRouting27import com.google.gson.Gson28import org.apache.commons.codec.binary.Base6429import org.json.JSONObject30import java.io.ByteArrayInputStream31import java.io.ByteArrayOutputStream32import java.io.File33import java.io.FileOutputStream34import java.util.*35/**36 * @author Armel FAGBEDJI ( armel.fagbedji@opensi.co )37 * created at 01/03/201938 */39object Kkiapay{40 private lateinit var me: Me41 /**42 * Initialize SDK.43 * This function didn't check your API keys but keep it for future requests44 * @param apiKey developer prod / test API keys check https://kkiapay.me45 * @param context Application Context46 * @param sdkConfig SDK configurations. It is optional47 */48 @JvmOverloads49 @JvmStatic50 fun init(context: Context,51 apiKey:String,52 sdkConfig: SdkConfig = SdkConfig()) {53 me = Me(context, apiKey, sdkConfig)54 }55 /**56 * Recover the Kkiapay instance to perform actions57 * @return [Me] Instance of Kkiapay58 * @exception [IllegalAccessException] If the SDK was not initialized before use59 */60 @JvmStatic61 fun get(): Me {62 if (!Kkiapay::me.isInitialized)63 throw IllegalAccessException("You must initialise Kkiapay SDK in the onCreate methode of your App's" +64 " Application first")65 return me66 }67}68class Me internal constructor(context: Context, private val apiKey: String, private val sdkConfig: SdkConfig) {69 private var requestPaymentAction: RequestPaymentAction? = null70 private var sdkListener: ((STATUS, String?) -> Unit)? = null71 /**72 * MomoPay Instance73 */74 val momoPay: MomoPay75 init {76 KKiapayApi.apiKey = apiKey77 sdkConfig.run {78 convertColorToString(context)79 convertImageResToImageUrl(context)80 }81 momoPay = MomoPay(apiKey)82 }83 /**84 * Make a payment request85 * @param activity Payment activity86 * @param amount Amount to be paid87 * @param reason Payment description88 * @param name The name of the client89 * @param phone The customer's phone number90 * @param sandbox Make request on sandbox91 * @param data The callback redirect data92 * @exception [IllegalAccessException] If a listener was not configured on the UI-SDK93 */94 @JvmOverloads95 fun requestPayment(activity: AppCompatActivity,96 amount: String,97 reason: String,98 name: String,99 phone: String = "",100 callback: String = KKIAPAY_REDIRECT_URL,101 data: String = "",102 sandbox: Boolean = sdkConfig.enableSandbox103 ){104 sdkListener ?: throw IllegalAccessException("Sdk Listener is null, you must setup one before the call of" +105 " \"requestPayment\" methode")106 sdkConfig.enableSandbox = sandbox107 KKIAPAY_REDIRECT_URL = callback108 val user = User(amount, reason, name, apiKey, callback, phone, sandbox = sandbox, data = data)109 requestPaymentAction = RequestPaymentAction(user)110 requestPaymentAction?.invoke(activity, sdkConfig)111 }112 /**113 * Configure a listener for the UI-SDK, to manage the information returned by the latter114 * @param listener mandatory115 */116 fun setListener(listener: (STATUS, String?) -> Unit): Me {117 sdkListener = listener118 return this119 }120 /**121 * Remove UI-SDK listener122 */123 fun removeSdkListener(){124 sdkListener = null125 }126 /**127 * To call in onActivityResult of your activity to manage the return response128 * the UI-SDK using the [sdkListener] which was initially informed129 */130 fun handleActivityResult(requestCode: Int, resultCode: Int, data: Intent?){131 if (requestCode == KKIAPAY_REQUEST_CODE && resultCode == Activity.RESULT_OK){132 data?.run {133 if (hasExtra(KKIAPAY_TRANSACTION_ID)){134 val transactionId = getStringExtra(KKIAPAY_TRANSACTION_ID)135 transactionId?.let {136 (if (sdkConfig.enableSandbox) ::sandboxCheckTransactionStatus137 else ::checkTransactionStatus).invoke(it)138 .responseString { _, _, result ->139 result.fold({ resutlString ->140 val transaction = Gson().fromJson<Transaction>(resutlString, Transaction::class.java)141 sdkListener?.invoke(when(transaction.status){142 "SUCCESS" -> STATUS.SUCCESS143 "INVALID_TRANSACTION" -> STATUS.INVALID_TRANSACTION144 "TRANSACTION_NOT_FOUND" -> STATUS.TRANSACTION_NOT_FOUND145 "FAILED" -> STATUS.FAILED146 else -> STATUS.UNKNOWN147 },148 transaction.transactionId)149 }){fuelError ->150 Log.i("Kkiapay.me", fuelError.toString())151 val theError = Gson().fromJson<Error>(String(fuelError.errorData), Error::class.java)152 theError?.let {error ->153 sdkListener?.invoke(when(error.status) {154 4001 -> STATUS.INVALID_PHONE_NUMBER155 4003 -> STATUS.INVALID_API_KEY156 else -> STATUS.FAILED157 }, null)158 } ?: kotlin.run {159 sdkListener?.invoke(STATUS.FAILED, null)160 }161 }162 }163 } ?: kotlin.run {164 sdkListener?.invoke(STATUS.SUCCESS, null)165 }166 } else167 sdkListener?.invoke(STATUS.SUCCESS, null)168 } ?: let {169 sdkListener?.invoke(STATUS.SUCCESS, null)170 }171 } else{172 sdkListener?.invoke(STATUS.FAILED, null)173 }174 }175 companion object {176 internal const val KKIAPAY_URL = "https://widget-v2.kkiapay.me"177 internal var KKIAPAY_REDIRECT_URL = "http://redirect.kkiapay.me"178 const val KKIAPAY_REQUEST_CODE = 0xABC179 internal const val KKIAPAY_TRANSACTION_ID = "me.kkiapay.uikit.KKIAPAY_TRANSACTION_ID"180 }181}182/**183 * Configure and customize the UI-SDK.184 * Possibility to configure the color [themeColor]185 * and the shop logo [imageResource]186 */187data class SdkConfig(@RawRes private val imageResource: Int = -1, @ColorRes internal val themeColor: Int = -1, var enableSandbox: Boolean = false){188 internal var imageUrl: String = ""189 internal var color: String = ""190 internal fun convertColorToString(context: Context){191 if (themeColor != -1){192 color = String.format("#%06x", ContextCompat.getColor(context, themeColor) and 0xffffff)193 Log.i("Kkiapay.me", color)194 }195 }196 internal fun convertImageResToImageUrl(context: Context){197 if (imageResource != -1){198 val stream = context.resources.openRawResource(imageResource)199 var bitmap = BitmapFactory.decodeStream(stream)200 bitmap = reduceBitmap(bitmap)201 val file = File(context.cacheDir, "${UUID.randomUUID()}.png")202 FileOutputStream(file).use {203 bitmap.compress(Bitmap.CompressFormat.PNG, 0, it)204 it.flush()205 }206 KKiapayApi.uploadFile(file)207 ?.responseString { _, _, result ->208 result.fold({resutlString ->209 val uploadKey = Gson().fromJson<List<Map<String, String>>>(resutlString, List::class.java)210 .first()["fd"]?.trim()211 imageUrl = KKiapayApi.getUploadedFile(uploadKey)?.url?.toString() ?: ""212 }){213 Log.e("Kkiapay.me", it.toString())214 }215 }216 }217 }218 private fun reduceBitmap(original: Bitmap): Bitmap {219 val out = ByteArrayOutputStream()220 original.compress(Bitmap.CompressFormat.WEBP, 100, out)221 return BitmapFactory.decodeStream(ByteArrayInputStream(out.toByteArray()))222 }223}224internal class RequestPaymentAction(private val user: User) {225 operator fun invoke(activity: AppCompatActivity, sdkConfig: SdkConfig){226 activity.startActivityForResult(227 Intent(activity, CustomTabActivity::class.java).apply {228 putExtra(CustomTabActivity.EXTRA_URL,229 "$KKIAPAY_URL/?=${user.toBase64(activity.applicationContext, sdkConfig)}")230 putExtra(CustomTabActivity.EXTRA_THEME,231 sdkConfig.themeColor)232 }, KKIAPAY_REQUEST_CODE)233 }234}235internal data class User(val amount: String = "",236 val reason: String = "",237 val name: String = "",238 val key: String = "",239 val callback: String,240 val phone: String = "",241 val sdk: String = "android",242 val theme: String = "",243 val url: String = "",244 val sandbox: Boolean,245 val host: String? = "",246 val data: String = ""247) {248 fun toBase64(context: Context, sdkConfig: SdkConfig) : String{249 val preConvertion = this.copy(250 theme = sdkConfig.color,251 url = sdkConfig.imageUrl,252 host = context.applicationContext.packageName253 )254 val userJson = Gson().toJson(preConvertion).toString()255 return String(Base64.encodeBase64(userJson.toByteArray()))256 }257}258private sealed class SandBoxKKiapayApi : FuelRouting {259 override val basePath: String260 get() = "https://api-sandbox.kkiapay.me"261 override val headers: Map<String, HeaderValues>?262 get() = mapOf("x-api-key" to listOf(KKiapayApi.apiKey))263 override val method: Method264 get() = Method.POST265 override val body: String?266 get() = null267 override val bytes: ByteArray?268 get() = null269 override val params: Parameters?270 get() = emptyList()271 private class SandBoxCheckTansactionStatus(private val transactionId: String): SandBoxKKiapayApi() {272 override val path: String273 get() = "/api/v1/transactions/status"274 override val headers: Map<String, HeaderValues>?275 get() = super.headers?.plus("Content-Type" to listOf("application/json"))276 override val body: String?277 get() = JSONObject().putOpt("transactionId", transactionId).toString()278 }279 companion object {280 internal fun sandboxCheckTransactionStatus(transactionId: String) =281 Fuel.request(SandBoxCheckTansactionStatus(transactionId))282 }283}284private sealed class KKiapayApi : FuelRouting {285 override val basePath: String286 get() = "https://api.kkiapay.me"287 override val headers: Map<String, HeaderValues>?288 get() = mapOf("x-api-key" to listOf(apiKey))289 override val method: Method290 get() = Method.POST291 override val body: String?292 get() = null293 override val bytes: ByteArray?294 get() = null295 override val params: Parameters?296 get() = emptyList()297 private class UploadFile(private val classification: String = "android_client_store_icon"): KKiapayApi(){298 override val path: String299 get() = "/utils/upload"300 override val params: List<Pair<String, Any?>>?301 get() = listOf("type" to classification)302 }303 private class CheckTansactionStatus(private val transactionId: String): KKiapayApi() {304 override val path: String305 get() = "/api/v1/transactions/status"306 override val headers: Map<String, HeaderValues>?307 get() = super.headers?.plus("Content-Type" to listOf("application/json"))308 override val body: String?309 get() = JSONObject().putOpt("transactionId", transactionId).toString()310 }311 private class GetUploadedFile(private val fileKey: String): KKiapayApi() {312 override val path: String313 get() = "/utils/file/$fileKey"314 override val method: Method315 get() = Method.GET316 }317 companion object {318 internal lateinit var apiKey: String319 internal fun uploadFile(file: File?) =320 file?.run { Fuel.request(UploadFile())321 .upload()322 .add { FileDataPart(this, name = "file") } }323 internal fun checkTransactionStatus(transactionId: String) =324 Fuel.request(CheckTansactionStatus(transactionId))325 internal fun getUploadedFile(fileKey: String?) =326 fileKey?.run{327 Fuel.request(GetUploadedFile(fileKey))328 }329 }330}...

Full Screen

Full Screen

sms.kt

Source:sms.kt Github

copy

Full Screen

1package kr.jadekim.ncloud.sens.protocol2import com.github.kittinunf.fuel.util.encodeBase643import com.google.gson.TypeAdapter4import com.google.gson.annotations.SerializedName5import com.google.gson.stream.JsonReader6import com.google.gson.stream.JsonWriter7import kr.jadekim.ncloud.sens.enumeration.Country8import kr.jadekim.ncloud.sens.enumeration.SmsContentType9import kr.jadekim.ncloud.sens.enumeration.SmsReserveStatus10import kr.jadekim.ncloud.sens.enumeration.SmsType11class SendSms {12 data class Request(13 val type: SmsType,14 val contentType: SmsContentType,15 @SerializedName("countryCode") val county: Country,16 val from: String,17 val subject: String?,18 val content: String,19 val messages: List<Message>?,20 val files: List<Attachment>?,21 val reserveTime: String?,22 val reserveTimeZone: String?,23 val scheduleCode: String?24 ) {25 data class Message(26 val to: String,27 val subject: String?,28 val content: String?29 )30 data class Attachment(31 val name: String?,32 @SerializedName("body") val encodedBody: String?33 ) {34 constructor(name: String?, body: ByteArray?) : this(name, body?.let { String(it.encodeBase64()) })35 }36 }37 data class Response(38 val requestId: String,39 val requestTime: String,40 val statusCode: String,41 val statusName: String42 )43}44class GetSendSmsRequest {45 data class Response(46 val requestId: String,47 val statusCode: String,48 val statusName: String,49 val messages: List<Message>50 ) {51 data class Message(52 val messageId: String,53 val requestTime: String,54 val contentType: SmsContentType,55 @SerializedName("countryCode") val county: Country,56 val from: String,57 val to: String58 )59 }60}61class GetSendSmsResult {62 data class Response(63 val statusCode: String,64 val statusName: String,65 val messages: List<Message>66 ) {67 data class Message(68 val requestTime: String,69 val contentType: SmsContentType,70 val content: String,71 @SerializedName("countryCode") val country: String,72 val from: String,73 val to: String,74 val status: EmmaResultCode,75 val statusCode: EmmaResultCode,76 val statusMessage: String,77 val completeTime: String,78 val telcoCode: String,79 val files: List<Attachment>?80 )81 data class Attachment(82 val name: String?83 )84 }85}86class GetSmsReservationStatus {87 data class Response(88 val reserveId: String,89 val reserveTime: String,90 val reserveTimeZone: String,91 val reserveStatus: SmsReserveStatus92 )93}94class EmmaResultCode(val code: String) {95 val isSuccess = code == "0"96 val description by lazy {97 when (code) {98 //IB G/W Report Code : 이통사 전송 후 받은 결과코드99 "0" -> "성공"100 "2000" -> "전송 시간 초과"101 "2001" -> "전송 실패 (무선망단)"102 "2002" -> "전송 실패 (무선망 -> 단말기단)"103 "2003" -> "단말기 전원 꺼짐"104 "2004" -> "단말기 메시지 버퍼 풀"105 "2005" -> "음영지역"106 "2006" -> "메시지 삭제됨"107 "2007" -> "일시적인 단말 문제"108 "3000" -> "전송할 수 없음"109 "3001" -> "가입자 없음"110 "3002" -> "성인 인증 실패"111 "3003" -> "수신번호 형식 오류"112 "3004" -> "단말기 서비스 일시 정지"113 "3005" -> "단말기 호 처리 상태"114 "3006" -> "착신 거절"115 "3007" -> "Callback URL 을 받을 수 없는 폰"116 "3008" -> "기타 단말기 문제"117 "3009" -> "메시지 형식 오류"118 "3010" -> "MMS 미지원 단말"119 "3011" -> "서버 오류"120 "3012" -> "스팸"121 "3013" -> "서비스 거부"122 "3014" -> "기타"123 "3015" -> "전송 경로 없음"124 "3016" -> "첨부파일 사이즈 제한 실패"125 "3017" -> "발신번호 변작 방지 세칙 위반"126 "3018" -> "발신번호 변작 방지 서비스에 가입된 휴대폰 개인가입자 번호"127 "3019" -> "KISA 또는 미래부에서 모든 고객사에 대하여 차단 처리 요청한 발신번호"128 "3022" -> "Charset Conversion Error"129 "3023" -> "발신번호 사전등록제를 통해 등록되지 않은 번호"130 //IB G/W Response Code : Infobank G/W가 메시지 수신 후 주는 결과코드131 "1001" -> "Server Busy (RS 내부 저장 Queue Full)"132 "1002" -> "수신번호 형식 오류"133 "1003" -> "회신번호 형식 오류"134 "1004" -> "SPAM"135 "1005" -> "사용 건수 초과"136 "1006" -> "첨부 파일 없음"137 "1007" -> "첨부 파일 있음"138 "1008" -> "첨부 파일 저장 실패"139 "1009" -> "CLIENT_MSG_KEY 없음"140 "1010" -> "CONTENT 없음"141 "1011" -> "CALLBACK 없음"142 "1012" -> "RECIPIENT_INFO 없음"143 "1013" -> "SUBJECT 없음"144 "1014" -> "첨부 파일 KEY 없음"145 "1015" -> "첨부 파일 NAME 없음"146 "1016" -> "첨부 파일 크기 없음"147 "1017" -> "첨부 파일 Content 없음"148 "1018" -> "전송 권한 없음"149 "1019" -> "TTL 초과"150 "1020" -> "charset conversion error"151 //IB EMMA : EMMA가 메시지 전송 요청에 대해 처리한 오류 코드152 "E900" -> "Invalid-IB 전송키가 없는 경우"153 "E901" -> "수신번호가 없는 경우"154 "E902" -> "동보인 경우) 수신번소순번이 없는 경우"155 "E903" -> "제목 없는 경우"156 "E904" -> "메시지가 없는 경우"157 "E905" -> "회신번호가 없는 경우"158 "E906" -> "메시지키가 없는 경우"159 "E907" -> "동보 여부가 없는 경우"160 "E908" -> "서비스 타입이 없는 경우"161 "E909" -> "전송 요청 시각이 없는 경우"162 "E910" -> "TTL 타임이 없는 경우"163 "E911" -> "서비스 타입이 MMS MT인 경우, 첨부파일 확장자가 없는 경우"164 "E912" -> "서비스 타입이 MMS MT인 경우, attach_file 폴더에 첨부파일이 없는 경우"165 "E913" -> "서비스 타입이 MMS MT인 경우, 첨부파일 사이즈가 0인 경우"166 "E914" -> "서비스 타입이 MMS MT인 경우, 메시지 테이블에는 파일그룹키가 있는데 파일 테이블에 데이터가 없는 경우"167 "E915" -> "중복메시지"168 "E916" -> "인증서버 차단번호"169 "E917" -> "고객DB 차단번호"170 "E918" -> "USER CALLBACK FAIL"171 "E919" -> "발송 제한 시간인 경우, 메시지 재발송 처리가 금지된 경우"172 "E920" -> "서비스 타입이 LMS MT인 경우, 메시지 테이블에 파일그룹키가 있는 경우"173 "E921" -> "서비스 타입이 LMS MT인 경우, 메시지 테이블에 파일그룹키가 없는 경우"174 "E922" -> "동보단어 제약문자 사용 오류"175 "E999" -> "기타 오류"176 else -> "알 수 없는 오류"177 }178 }179 object GsonAdapter : TypeAdapter<EmmaResultCode>() {180 override fun write(out: JsonWriter, value: EmmaResultCode?) {181 out.value(value?.code)182 }183 override fun read(input: JsonReader): EmmaResultCode = EmmaResultCode(input.nextString())184 }185}...

Full Screen

Full Screen

RoutingTest.kt

Source:RoutingTest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.HeaderValues4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.core.Parameters6import com.github.kittinunf.fuel.test.MockHttpTestCase7import com.github.kittinunf.fuel.util.FuelRouting8import com.github.kittinunf.fuel.util.decodeBase64ToString9import com.github.kittinunf.fuel.util.encodeBase6410import org.hamcrest.CoreMatchers.containsString11import org.hamcrest.CoreMatchers.notNullValue12import org.hamcrest.CoreMatchers.nullValue13import org.json.JSONObject14import org.junit.Assert.assertThat15import org.junit.Test16import java.net.HttpURLConnection17import org.hamcrest.CoreMatchers.`is` as isEqualTo18class RoutingTest : MockHttpTestCase() {19 private val manager: FuelManager by lazy { FuelManager() }20 sealed class TestApi(private val host: String) : FuelRouting {21 override val basePath = this.host22 class GetTest(host: String) : TestApi(host)23 class GetParamsTest(host: String, val name: String, val value: String) : TestApi(host)24 class PostBodyTest(host: String, val value: String) : TestApi(host)25 class PostBinaryBodyTest(host: String, val value: String) : TestApi(host)26 class PostEmptyBodyTest(host: String) : TestApi(host)27 override val method: Method28 get() {29 return when (this) {30 is GetTest -> Method.GET31 is GetParamsTest -> Method.GET32 is PostBodyTest -> Method.POST33 is PostBinaryBodyTest -> Method.POST34 is PostEmptyBodyTest -> Method.POST35 }36 }37 override val path: String38 get() {39 return when (this) {40 is GetTest -> "/get"41 is GetParamsTest -> "/get"42 is PostBodyTest -> "/post"43 is PostBinaryBodyTest -> "/post"44 is PostEmptyBodyTest -> "/post"45 }46 }47 override val params: Parameters?48 get() {49 return when (this) {50 is GetParamsTest -> listOf(this.name to this.value)51 else -> null52 }53 }54 override val bytes: ByteArray?55 get() {56 return when (this) {57 is PostBinaryBodyTest -> {58 val json = JSONObject()59 json.put("id", this.value)60 json.toString().toByteArray().encodeBase64()61 }62 else -> null63 }64 }65 override val body: String?66 get() {67 return when (this) {68 is PostBodyTest -> {69 val json = JSONObject()70 json.put("id", this.value)71 json.toString()72 }73 else -> null74 }75 }76 override val headers: Map<String, HeaderValues>?77 get() {78 return when (this) {79 is PostBodyTest -> mapOf("Content-Type" to listOf("application/json"))80 is PostBinaryBodyTest -> mapOf("Content-Type" to listOf("application/octet-stream"))81 is PostEmptyBodyTest -> mapOf("Content-Type" to listOf("application/json"))82 else -> null83 }84 }85 }86 @Test87 fun httpRouterGet() {88 mock.chain(89 request = mock.request().withMethod(Method.GET.value),90 response = mock.reflect()91 )92 val (request, response, result) = manager.request(TestApi.GetTest(mock.path(""))).responseString()93 val (data, error) = result94 assertThat(request, notNullValue())95 assertThat(response, notNullValue())96 assertThat(error, nullValue())97 assertThat(data, notNullValue())98 val statusCode = HttpURLConnection.HTTP_OK99 assertThat(response.statusCode, isEqualTo(statusCode))100 }101 @Test102 fun httpRouterGetParams() {103 mock.chain(104 request = mock.request().withMethod(Method.GET.value),105 response = mock.reflect()106 )107 val paramKey = "foo"108 val paramValue = "bar"109 val (request, response, result) = manager.request(TestApi.GetParamsTest(host = mock.path(""), name = paramKey, value = paramValue)).responseString()110 val (data, error) = result111 val string = data as String112 assertThat(request, notNullValue())113 assertThat(response, notNullValue())114 assertThat(error, nullValue())115 assertThat(data, notNullValue())116 val statusCode = HttpURLConnection.HTTP_OK117 assertThat(response.statusCode, isEqualTo(statusCode))118 assertThat(string, containsString(paramKey))119 assertThat(string, containsString(paramValue))120 }121 @Test122 fun httpRouterPostBody() {123 mock.chain(124 request = mock.request().withMethod(Method.POST.value),125 response = mock.reflect()126 )127 val paramValue = "42"128 val (request, response, result) = manager.request(TestApi.PostBodyTest(mock.path(""), paramValue)).responseString()129 val (data, error) = result130 val string = JSONObject(data).getJSONObject("body").getString("string")131 assertThat(request, notNullValue())132 assertThat(response, notNullValue())133 assertThat(error, nullValue())134 assertThat(data, notNullValue())135 val statusCode = HttpURLConnection.HTTP_OK136 assertThat(response.statusCode, isEqualTo(statusCode))137 val res = JSONObject(string)138 assertThat(res.getString("id"), isEqualTo(paramValue))139 }140 @Test141 fun httpRouterPostBinaryBody() {142 mock.chain(143 request = mock.request().withMethod(Method.POST.value),144 response = mock.reflect()145 )146 val paramValue = "42"147 val (request, response, result) = manager.request(TestApi.PostBinaryBodyTest(mock.path(""), paramValue)).responseString()148 val (data, error) = result149 // Binary data is encoded in base64 by mock server150 val string = JSONObject(data).getJSONObject("body").getString("base64Bytes").decodeBase64ToString()151 assertThat(request, notNullValue())152 assertThat(response, notNullValue())153 assertThat(error, nullValue())154 assertThat(data, notNullValue())155 val statusCode = HttpURLConnection.HTTP_OK156 assertThat(response.statusCode, isEqualTo(statusCode))157 val bytes = string!!.decodeBase64ToString()158 assertThat(bytes, containsString(paramValue))159 }160 @Test161 fun httpRouterPostEmptyBody() {162 mock.chain(163 request = mock.request().withMethod(Method.POST.value),164 response = mock.reflect()165 )166 val (request, response, result) = manager.request(TestApi.PostEmptyBodyTest(mock.path(""))).responseString()167 val (data, error) = result168 val string = data as String169 assertThat(request, notNullValue())170 assertThat(response, notNullValue())171 assertThat(error, nullValue())172 assertThat(data, notNullValue())173 val statusCode = HttpURLConnection.HTTP_OK174 assertThat(response.statusCode, isEqualTo(statusCode))175 val res = JSONObject(string)176 assertThat(res.optString("data"), isEqualTo(""))177 }178}...

Full Screen

Full Screen

Base64.kt

Source:Base64.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.util2/**3 * Inspired From https://github.com/square/okio/blob/master/okio/src/main/kotlin/okio/-Base64.kt4 */5import java.lang.System.arraycopy6fun ByteArray.encodeBase64(): ByteArray = encodeBase64ToArray()7fun ByteArray.encodeBase64Url(): ByteArray = encodeBase64ToArray(map = BASE64_URL_SAFE)8fun String.encodeBase64ToString(): String = String(toByteArray().encodeBase64())9fun String.encodeBase64UrlToString(): String = String(toByteArray().encodeBase64Url())10fun String.decodeBase64(): ByteArray? = decodeBase64ToArray()?.let { it }11fun String.decodeBase64ToString(): String? = decodeBase64ToArray()?.let { String(it) }12private val regular = listOf(('A'..'Z'), ('a'..'z'), ('0'..'9'), listOf('+', '/'))13private val urlSafe = listOf(('A'..'Z'), ('a'..'z'), ('0'..'9'), listOf('-', '_'))14private val BASE64 = regular.flatten().map { it.toByte() }.toByteArray()15private val BASE64_URL_SAFE = urlSafe.flatten().map { it.toByte() }.toByteArray()16private fun ByteArray.encodeBase64ToArray(map: ByteArray = BASE64): ByteArray {17 val length = (size + 2) / 3 * 418 val out = ByteArray(length)19 var index = 020 val end = size - size % 321 var i = 022 while (i < end) {23 val b0 = this[i++].toInt()24 val b1 = this[i++].toInt()25 val b2 = this[i++].toInt()26 out[index++] = map[(b0 and 0xff shr 2)]27 out[index++] = map[(b0 and 0x03 shl 4) or (b1 and 0xff shr 4)]28 out[index++] = map[(b1 and 0x0f shl 2) or (b2 and 0xff shr 6)]29 out[index++] = map[(b2 and 0x3f)]30 }31 when (size - end) {32 1 -> {33 val b0 = this[i].toInt()34 out[index++] = map[b0 and 0xff shr 2]35 out[index++] = map[b0 and 0x03 shl 4]36 out[index++] = '='.toByte()37 out[index] = '='.toByte()38 }39 2 -> {40 val b0 = this[i++].toInt()41 val b1 = this[i].toInt()42 out[index++] = map[(b0 and 0xff shr 2)]43 out[index++] = map[(b0 and 0x03 shl 4) or (b1 and 0xff shr 4)]44 out[index++] = map[(b1 and 0x0f shl 2)]45 out[index] = '='.toByte()46 }47 }48 return out49}50private fun String.decodeBase64ToArray(): ByteArray? {51 // Ignore trailing '=' padding and whitespace from the input.52 var limit = length53 while (limit > 0) {54 val c = this[limit - 1]55 if (c != '=' && c != '\n' && c != '\r' && c != ' ' && c != '\t') {56 break57 }58 limit--59 }60 // If the input includes whitespace, this output array will be longer than necessary.61 val out = ByteArray((limit * 6L / 8L).toInt())62 var outCount = 063 var inCount = 064 var word = 065 for (pos in 0 until limit) {66 val c = this[pos]67 val bits: Int68 if (c in 'A'..'Z') {69 // char ASCII value70 // A 65 071 // Z 90 25 (ASCII - 65)72 bits = c.toInt() - 6573 } else if (c in 'a'..'z') {74 // char ASCII value75 // a 97 2676 // z 122 51 (ASCII - 71)77 bits = c.toInt() - 7178 } else if (c in '0'..'9') {79 // char ASCII value80 // 0 48 5281 // 9 57 61 (ASCII + 4)82 bits = c.toInt() + 483 } else if (c == '+' || c == '-') {84 bits = 6285 } else if (c == '/' || c == '_') {86 bits = 6387 } else if (c == '\n' || c == '\r' || c == ' ' || c == '\t') {88 continue89 } else {90 return null91 }92 // Append this char's 6 bits to the word.93 word = word shl 6 or bits94 // For every 4 chars of input, we accumulate 24 bits of output. Emit 3 bytes.95 inCount++96 if (inCount % 4 == 0) {97 out[outCount++] = (word shr 16).toByte()98 out[outCount++] = (word shr 8).toByte()99 out[outCount++] = word.toByte()100 }101 }102 val lastWordChars = inCount % 4103 when (lastWordChars) {104 1 -> {105 // We read 1 char followed by "===". But 6 bits is a truncated byte! Fail.106 return null107 }108 2 -> {109 // We read 2 chars followed by "==". Emit 1 byte with 8 of those 12 bits.110 word = word shl 12111 out[outCount++] = (word shr 16).toByte()112 }113 3 -> {114 // We read 3 chars, followed by "=". Emit 2 bytes for 16 of those 18 bits.115 word = word shl 6116 out[outCount++] = (word shr 16).toByte()117 out[outCount++] = (word shr 8).toByte()118 }119 }120 // If we sized our out array perfectly, we're done.121 if (outCount == out.size) return out122 // Copy the decoded bytes to a new, right-sized array.123 val prefix = ByteArray(outCount)124 arraycopy(out, 0, prefix, 0, outCount)125 return prefix126}...

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.util.Base642val encodedString = Base64.encodeBase64(byteArray)3val decodedByteArray = Base64.decodeBase64(encodedString)4val decodedString = Base64.decodeBase64ToString(encodedString)5val decodedString = Base64.decodeBase64ToString(byteArray)6val encodedString = Base64.encodeBase64ToString(byteArray)7val encodedString = Base64.encodeBase64ToString(string)8val encodedString = Base64.encodeBase64ToString(string, charset)9val encodedString = Base64.encodeBase64ToString(byteArray, charset)10val encodedString = Base64.encodeBase64ToString(byteArray, offset, len)11val encodedString = Base64.encodeBase64ToString(byteArray, offset, len, charset)12val decodedByteArray = Base64.decodeBase64(encodedString, charset)13val decodedString = Base64.decodeBase64ToString(encodedString, charset)14val decodedString = Base64.decodeBase64ToString(byteArray, charset)

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1val encoded = Base64.encodeBase64(byteArray)2val decoded = Base64.decodeBase64(encoded)3val encodedString = Base64.encodeBase64String(byteArray)4val decodedString = Base64.decodeBase64String(encodedString)5val encoded = Base64.encodeBase64(byteArray)6val decoded = Base64.decodeBase64(encoded)7val encodedString = Base64.encodeBase64String(byteArray)8val decodedString = Base64.decodeBase64String(encodedString)9val encoded = Base64.encodeBase64(byteArray)10val decoded = Base64.decodeBase64(encoded)11val encodedString = Base64.encodeBase64String(byteArray)12val decodedString = Base64.decodeBase64String(encodedString)13val encoded = Base64.encodeBase64(byteArray)14val decoded = Base64.decodeBase64(encoded)

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1 val base64EncodedString = ByteArray(0).encodeBase64()2 val byteArray = base64EncodedString.decodeBase64()3 val base64EncodedString = byteArray.toBase64()4 val byteArray = base64EncodedString.fromBase64()5 val base64EncodedString = ByteArray(0).encodeBase64()6 val byteArray = base64EncodedString.decodeBase64()7 val base64EncodedString = byteArray.toBase64()8 val byteArray = base64EncodedString.fromBase64()9 val base64EncodedString = ByteArray(0).encodeBase64()10 val byteArray = base64EncodedString.decodeBase64()11 val base64EncodedString = byteArray.toBase64()12 val byteArray = base64EncodedString.fromBase64()

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray())2val base64Decoded = ByteArray.decodeBase64(base64Encoded)3val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray())4val base64Decoded = ByteArray.decodeBase64(base64Encoded)5val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), java.util.Base64.getEncoder())6val base64Decoded = ByteArray.decodeBase64(base64Encoded, java.util.Base64.getDecoder())7val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), com.github.kittinunf.fuel.util.Base64.getEncoder())8val base64Decoded = ByteArray.decodeBase64(base64Encoded, com.github.kittinunf.fuel.util.Base64.getDecoder())9val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), com.github.kittinunf.fuel.util.Base64.getEncoder())10val base64Decoded = ByteArray.decodeBase64(base64Encoded, com.github.kittinunf.fuel.util.Base64.getDecoder())11val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), com.github.kittinunf.fuel.util.Base64.getEncoder())12val base64Decoded = ByteArray.decodeBase64(base64Encoded, com.github.kittinunf.fuel.util.Base

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1fun ByteArray.toBitmap(): Bitmap2fun ByteArray.toFile(fileName: String): File3fun ByteArray.encodeBase64(): String4fun ByteArray.decodeBase64(base64String: String): ByteArray5fun ByteArray.toBase64(): String6fun ByteArray.fromBase64(base64String: String): ByteArray7fun ByteArray.toHexadecimalString(): String8fun ByteArray.fromHexadecimalString(hexadecimalString: String): ByteArray

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1val encodedString = Base64.encodeBase64(byteArray)2val decodedByteArray = Base64.decodeBase64(encodedString)3val encodedByteArray = Base64.encodeBase64(byteArray)4val decodedByteArray = Base64.decodeBase64(encodedByteArray)5val encodedByteArray = Base64.encodeBase64(byteArray, Base64.NO_WRAP)6val decodedByteArray = Base64.decodeBase64(encodedByteArray, Base64.NO_WRAP)7val encodedByteArray = Base64.encodeBase64(byteArray, Base64.NO_WRAP or Base64.URL_SAFE)8val decodedByteArray = Base64.decodeBase64(encodedByteArray, Base64.NO_WRAP or Base64.URL_SAFE)9val encodedByteArray = Base64.encodeBase64(byteArray, Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING)10val decodedByteArray = Base64.decodeBase64(encodedByteArray, Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING)11fun ByteArray.fromBase64(base64String: String): ByteArray12fun ByteArray.toHexadecimalString(): String13fun ByteArray.fromHexadecimalString(hexadecimalString: String): ByteArray

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray())2val base64Decoded = ByteArray.decodeBase64(base64Encoded)3val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray())4val base64Decoded = ByteArray.decodeBase64(base64Encoded)5val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), java.util.Base64.getEncoder())6val base64Decoded = ByteArray.decodeBase64(base64Encoded, java.util.Base64.getDecoder())7val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), com.github.kittinunf.fuel.util.Base64.getEncoder())8val base64Decoded = ByteArray.decodeBase64(base64Encoded, com.github.kittinunf.fuel.util.Base64.getDecoder())9val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), com.github.kittinunf.fuel.util.Base64.getEncoder())10val base64Decoded = ByteArray.decodeBase64(base64Encoded, com.github.kittinunf.fuel.util.Base64.getDecoder())11val base64Encoded = ByteArray.encodeBase64("Hello, world!".toByteArray(), com.github.kittinunf.fuel.util.Base64.getEncoder())12val base64Decoded = ByteArray.decodeBase64(base64Encoded, com.github.kittinunf.fuel.util.Base

Full Screen

Full Screen

ByteArray.encodeBase64

Using AI Code Generation

copy

Full Screen

1fun ByteArray.toBitmap(): Bitmap2fun ByteArray.toFile(fileName: String): File3fun ByteArray.encodeBase64(): String4fun ByteArray.decodeBase64(base64String: String): ByteArray5fun ByteArray.toBase64(): String6fun ByteArray.fromBase64(base64String: String): ByteArray7fun ByteArray.toHexadecimalString(): String8fun ByteArray.fromHexadecimalString(hexadecimalString: String): ByteArray

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful