How to use success method of com.github.kittinunf.fuel.private class

Best Fuel code snippet using com.github.kittinunf.fuel.private.success

NetworkManager.kt

Source:NetworkManager.kt Github

copy

Full Screen

...100 when (result) {101 is com.github.kittinunf.result.Result.Success -> {102 try {103 val data: JSONObject = result.getAs<FuelJson>()?.obj() as JSONObject104 val success = data.getString("result") == "ok"105 val parkedCars = getParkedCarsFromResponse(data)106 if (success) {107 resultReadyListener(Result.Success(parkedCars))108 } else {109 resultReadyListener(Result.Fail(parkedCars, errorMessage))110 }111 } catch (e: org.json.JSONException) {112 val msg = "$errorMessage\n" +113 context.getString(R.string.fail_reason_unknown_data)114 resultReadyListener(Result.Fail(null, msg))115 } catch (e: Exception) {116 val msg = "$errorMessage\n" +117 context.getString(R.string.fail_reason_unknown_error)118 resultReadyListener(Result.Fail(null, msg))119 }120 }...

Full Screen

Full Screen

MessageHandler.kt

Source:MessageHandler.kt Github

copy

Full Screen

...178 }179 .responseObject(object : ResponseDeserializable<Unit> {180 override fun deserialize(reader: Reader) =181 runBlocking(Dispatchers.IO + CoroutineName("msgReceiver")) {182 logger.info("connected successfully")183 connectErrors = 0184 reconnectCooldown = 0185 reader.useLines { lines ->186 lines.forEach { line ->187 val msg = ApiMessage.decode(line)188 logger.debug("received: $msg")189 if (msg.event != "api_connect") {190 messageStream.send(msg)191 }192 }193 }194 }195 })196 when (result) {...

Full Screen

Full Screen

MojangKt.kt

Source:MojangKt.kt Github

copy

Full Screen

1package dev.dewy.mojangkt2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.gson.jsonBody4import com.github.kittinunf.fuel.gson.responseObject5import com.github.kittinunf.fuel.httpDelete6import com.github.kittinunf.fuel.httpGet7import com.github.kittinunf.fuel.httpPost8import com.github.kittinunf.fuel.httpPut9import com.github.kittinunf.result.Result10import com.google.gson.Gson11import com.google.gson.JsonObject12import java.util.Base6413import java.util.UUID14import java.util.regex.Pattern15import kotlin.coroutines.resume16import kotlin.coroutines.resumeWithException17import kotlin.coroutines.suspendCoroutine18class MojangKt {19 private val gson = Gson()20 @Suppress("UNUSED")21 var token = ""22 set(value) {23 field = value24 if (value.isEmpty()) {25 FuelManager.instance.baseHeaders = emptyMap()26 return27 }28 FuelManager.instance.baseHeaders = mapOf(29 "Authorization" to "Bearer $value"30 )31 }32 suspend fun getPlayerFromName(name: String): PrimitivePlayer = suspendCoroutine { cont ->33 "https://api.mojang.com/users/profiles/minecraft/$name"34 .httpGet()35 .responseObject<PrimitivePlayer> { _, _, result ->36 when (result) {37 is Result.Failure -> {38 cont.resumeWithException(result.getException())39 }40 is Result.Success -> {41 cont.resume(result.value)42 }43 }44 }45 }46 suspend fun getPlayersFromNames(names: List<String>): List<PrimitivePlayer> = suspendCoroutine { cont ->47 "https://api.mojang.com/profiles/minecraft"48 .httpPost()49 .jsonBody(50 names, gson51 )52 .responseObject<List<PrimitivePlayer>> { _, _, result ->53 when (result) {54 is Result.Failure -> {55 cont.resumeWithException(result.getException())56 }57 is Result.Success -> {58 cont.resume(result.value)59 }60 }61 }62 }63 suspend fun getProfileFromUuid(uuid: String): Profile = suspendCoroutine { cont ->64 "https://sessionserver.mojang.com/session/minecraft/profile/$uuid"65 .httpGet()66 .responseString {_, _, result ->67 when (result) {68 is Result.Failure -> {69 cont.resumeWithException(result.getException())70 }71 is Result.Success -> {72 val obj = gson.fromJson(result.value, JsonObject::class.java)73 val encodedProperties = obj["properties"].asJsonArray[0].asJsonObject["value"].asString74 val id = obj["id"].asString75 val name = obj["name"].asString76 val legacy = obj.has("legacy")77 var skinUrl = ""78 var skinType = getSkinType(id)79 var capeUrl = ""80 if (encodedProperties != null) {81 val texturesObj = gson.fromJson(String(Base64.getDecoder()82 .decode(encodedProperties)), JsonObject::class.java)83 .getAsJsonObject("textures")84 val skinObj = texturesObj.getAsJsonObject("SKIN")85 val capeObj = texturesObj.getAsJsonObject("CAPE")86 if (skinObj != null) {87 skinUrl = skinObj["url"].asString88 skinType = if (skinObj.has("metadata")) SkinType.SLIM else SkinType.DEFAULT89 }90 if (capeObj != null) {91 capeUrl = capeObj["url"].asString92 }93 }94 cont.resume(Profile(PrimitivePlayer(id, name, legacy), Skin(skinUrl, skinType), capeUrl))95 }96 }97 }98 }99 suspend fun getNameHistory(uuid: String): NameHistory = suspendCoroutine { cont ->100 "https://api.mojang.com/user/profiles/$uuid/names"101 .httpGet()102 .responseObject<List<NameHistoryNode>> { _, _, result ->103 when (result) {104 is Result.Failure -> {105 cont.resumeWithException(result.getException())106 }107 is Result.Success -> {108 cont.resume(NameHistory(result.value))109 }110 }111 }112 }113 suspend fun changeName(name: String) = suspendCoroutine<Unit> { cont ->114 "https://api.minecraftservices.com/minecraft/profile/name/$name"115 .httpPut()116 .response { _, response, result ->117 when (result) {118 is Result.Failure -> {119 when (response.statusCode) {120 400 -> cont.resumeWithException(InvalidNameException("Name must follow Mojang's name rules."))121 401 -> cont.resumeWithException(UnauthorizedAccessException("Token expired or incorrect."))122 403 -> cont.resumeWithException(UnavailableNameException("Name either taken or is in some other way unavailable."))123 500 -> cont.resumeWithException(TimedOutException("Timed out."))124 }125 }126 is Result.Success -> {127 cont.resume(Unit)128 }129 }130 }131 }132 suspend fun resetSkin(uuid: String) = suspendCoroutine<Unit> { cont ->133 "https://api.mojang.com/user/profile/$uuid/skin"134 .httpDelete()135 .responseString { _, _, result ->136 when (result) {137 is Result.Failure -> {138 cont.resumeWithException(result.getException())139 }140 is Result.Success -> {141 val errorObj = gson.fromJson(result.value, JsonObject::class.java)142 if (errorObj != null)143 cont.resumeWithException(MojangApiException("${errorObj["error"].asString}: ${errorObj["errorMessage"].asString}"))144 else145 cont.resume(Unit)146 }147 }148 }149 }150 suspend fun getBlockedServers(): List<String> = suspendCoroutine { cont ->151 "https://sessionserver.mojang.com/blockedservers"152 .httpGet()153 .responseString { _, _, result ->154 when (result) {155 is Result.Failure -> {156 cont.resumeWithException(result.getException())157 }158 is Result.Success -> {159 cont.resume(result.value.split("\n"))160 }161 }162 }163 }164 @Suppress("NAME_SHADOWING")165 private fun getSkinType(uuid: String): SkinType {166 val uuid = UUID.fromString(Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})")167 .matcher(uuid.replace("-", "")).replaceAll("$1-$2-$3-$4-$5"))168 return if ((uuid.hashCode() and 1) != 0)169 SkinType.SLIM170 else171 SkinType.DEFAULT172 }173}...

Full Screen

Full Screen

FuelWebService.kt

Source:FuelWebService.kt Github

copy

Full Screen

...10import com.google.gson.JsonSyntaxException11import me.shkschneider.skeleton.helper.ApplicationHelper12import me.shkschneider.skeleton.helperx.Logger13import java.util.concurrent.TimeUnit14import kotlin.Result.Companion.success15import kotlin.reflect.KClass16open class FuelWebService(val gson: Gson = Gson()) {17 init {18 if (ApplicationHelper.debuggable()) {19 FuelManager.instance.addRequestInterceptor { next: (Request) -> Request ->20 { request: Request ->21 Logger.info(request.toString())22 next(request)23 }24 }25 FuelManager.instance.addResponseInterceptor { next: (Request, Response) -> Response ->26 { request: Request, response: Response ->27 Logger.info(response.toString())28 next(request, response)29 }30 }31 }32 FuelManager.instance.timeoutInMillisecond = TimeUnit.SECONDS.toMillis(15).toInt()33 FuelManager.instance.timeoutReadInMillisecond = TimeUnit.SECONDS.toMillis(15).toInt()34 }35 inline fun <reified T: Any> get(url: String,36 crossinline success: (Request, Response, T) -> Unit,37 noinline failure: ((Request, Response, Exception) -> Unit)? = null38 ): Request = request<T>(Fuel.get(url), success, failure)39 inline fun <reified T: Any> head(url: String,40 crossinline success: (Request, Response, T) -> Unit,41 noinline failure: ((Request, Response, Exception) -> Unit)? = null42 ): Request = request<T>(Fuel.head(url), success, failure)43 inline fun <reified T: Any> post(url: String,44 crossinline success: (Request, Response, T) -> Unit,45 noinline failure: ((Request, Response, Exception) -> Unit)? = null46 ): Request = request<T>(Fuel.post(url), success, failure)47 inline fun <reified T: Any> put(url: String,48 crossinline success: (Request, Response, T) -> Unit,49 noinline failure: ((Request, Response, Exception) -> Unit)? = null50 ): Request = request<T>(Fuel.put(url), success, failure)51 inline fun <reified T: Any> delete(url: String,52 crossinline success: (Request, Response, T) -> Unit,53 noinline failure: ((Request, Response, Exception) -> Unit)? = null54 ): Request = request<T>(Fuel.delete(url), success, failure)55 @Deprecated("@hide")56 inline fun <reified T: Any> request(request: Request,57 crossinline success: (Request, Response, T) -> Unit,58 noinline failure: ((Request, Response, Exception) -> Unit)? = null59 ): Request = request.responseObject(Deserializer(gson, T::class)) { _, response, result: Result<T, FuelError> ->60 result.fold({ data ->61 success(request, response, data)62 }, { fuelError ->63 Logger.error("${fuelError.response.statusCode} ${fuelError.response.url}", fuelError.exception)64 failure?.invoke(request, response, fuelError.exception)65 })66 }67 inline fun <reified T: Any> deserialize(content: String): T? =68 Deserializer(gson, T::class).deserialize(content)69 inner class Deserializer<T: Any>(private val gson: Gson, private val klass: KClass<T>): ResponseDeserializable<T> {70 override fun deserialize(content: String): T? {71 try {72 return gson.fromJson(content, klass.java)73 } catch (e: JsonSyntaxException) {74 Logger.wtf(e)75 return null...

Full Screen

Full Screen

GMNetService.kt

Source:GMNetService.kt Github

copy

Full Screen

...40 }41 companion object {42 val instance: GMNetService by lazy { Holder.INSTANCE }43 }44 fun doRequest(remoteUrl: String, method: HttpMethod, params: List<Pair<String, Any?>>?, success: (Response) -> Unit, failed: (String) -> Unit) {45 Log.d(TAG, remoteUrl)46 async {47 Manager.instance.baseHeaders = mapOf("Cookie" to cookieManager.getCookie(apiHost))48 when (method) {49 HttpMethod.HttpMethodGet ->50 remoteUrl.httpGet(params).responseJson { _, response, _ ->51 uiThread {52 handleResponse(response, success, failed)53 }54 }55 HttpMethod.HttpMethodPost ->56 remoteUrl.httpPost(params).responseJson { _, response, _ ->57 uiThread {58 handleResponse(response, success, failed)59 }60 }61 HttpMethod.HttpMethodDelete ->62 remoteUrl.httpDelete(params).responseJson { _, response, _ ->63 uiThread {64 handleResponse(response, success, failed)65 }66 }67 HttpMethod.HttpMethodPut ->68 remoteUrl.httpPut(params).responseJson { request, response, result ->69 uiThread {70 handleResponse(response, success, failed)71 }72 }73 }74 }75 }76 fun handleResponse(response: Response, success: (Response) -> Unit, failed: (String) -> Unit) {77 Log.d(TAG, "handleResponse")78 val statusCode = response.httpStatusCode79 if (statusCode == HttpStatusCode.HttpStatusCodeSuccess.code) {80 success(response)81 } else if (statusCode == HttpStatusCode.HttpStatusCodeUnauthorized.code) {82 Log.d(TAG, "HttpStatusCode.HttpStatusCodeUnauthorized")83 this.sendLoginExpired()84 } else {85 failed("Request Data Error")86 }87 }88 fun sendLoginExpired() {89 val intent: Intent = Intent()90 intent.action = Constants.Broadcast.LoginExpired91 localBroadcastManager.sendBroadcast(intent)92 }93}...

Full Screen

Full Screen

QrScanResultDialog.kt

Source:QrScanResultDialog.kt Github

copy

Full Screen

1package com.example.easyin2import android.app.Dialog3import android.content.Context4import kotlinx.android.synthetic.main.qr_result_dialog.*5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.core.FuelError7import com.github.kittinunf.fuel.core.Request8import com.github.kittinunf.fuel.core.Response9import com.github.kittinunf.fuel.core.awaitResult10import com.github.kittinunf.fuel.core.extensions.jsonBody11import com.github.kittinunf.fuel.httpGet12import com.github.kittinunf.fuel.httpPost13import com.github.kittinunf.fuel.json.jsonDeserializer14import com.github.kittinunf.fuel.json.responseJson15import com.github.kittinunf.result.Result;16import org.json.JSONObject17import kotlin.reflect.typeOf18class QrScanResultDialog(var context : Context) {19 private lateinit var dialog: Dialog20 private var qrResultUrl : String = ""21 var email : String = ""22 init {23 initDialog()24 }25 private fun initDialog() {26 dialog = Dialog(context)27 dialog.setContentView(R.layout.qr_result_dialog)28 dialog.setCancelable(false)29 Onclicks()30 }31 fun show(qrResult: String) {32 qrResultUrl = qrResult33 dialog.scannedText.text = qrResultUrl34 email = qrResultUrl35 dialog.show()36 }37 private fun Onclicks() {38 dialog.postResult.setOnClickListener {39 postResult(qrResultUrl)40 }41 dialog.cancelDialog.setOnClickListener {42 dialog.dismiss()43 }44 }45// Adding an identity to the system46private fun postResult(Url: String) {47 val dataPOST = JSONObject()48 dataPOST.put("email", email)49 println(dataPOST)50 "http://oneeasyin.com:8080/identity/postidentity"51 .httpPost()52 .header("Content-Type" to "application/json")53 .body(dataPOST.toString()).responseJson {54 request, response, result ->55 when (result) {56 is Result.Failure -> {57 val ex = result.getException()58 println(ex)59 }60 is Result.Success -> {61 val data = result.get().obj()62 println(data)63 }64 }65 }66 }67 }...

Full Screen

Full Screen

ApiService.kt

Source:ApiService.kt Github

copy

Full Screen

1package com.example.kotlintestapp.auth2import android.content.ContentValues3import android.util.Log4import com.github.kittinunf.fuel.core.extensions.authentication5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.result.Result8import com.google.gson.Gson9import java.lang.Exception10class ApiService {11 private val clientId = "" //add clientId12 private val clientSecret = "" //add clientSecret13 private val apigeeTokenUrl = "" //add token url14 private val grantType = "client_credentials"15 var token: String? = null16 var tokenType: String? = null17 private fun callApi(apiEndpoint: String, tokenType: String, token: String): Any {18 val (request, response, result) = apiEndpoint19 .httpGet()20 .header(Pair("Authorization", "$tokenType $token"))21 .responseString()22 return when (result) {23 is Result.Success -> {24 Log.d(ContentValues.TAG, "Success ${result.value}")25 }26 is Result.Failure -> {27 Log.d(ContentValues.TAG, "Failed")28 }29 }30 }31 private fun setAuthToken() {32 try {33 val (request, response, result) = apigeeTokenUrl.httpPost(listOf(34 "grant_type" to grantType,35 ))36 .authentication().basic(clientId, clientSecret)37 .responseString()38 when (result) {39 is Result.Success -> {40 var gson = Gson()41 val tokenResultJson = gson.fromJson(result.value, AuthResult::class.java)42 token = tokenResultJson!!.access_token!!43 tokenType = tokenResultJson!!.token_type!!44 Log.d(ContentValues.TAG, "token $token")45 Log.d(ContentValues.TAG, "token type $tokenType")46 }47 is Result.Failure -> {48 // handle error49 println("error")50 }51 }52 }catch (e: Exception){53 e.printStackTrace()54 }55 }56 init {57 setAuthToken()58 callApi("https://..../getUsers", tokenType!!, token!!)59 }60}...

Full Screen

Full Screen

apiRepository.kt

Source:apiRepository.kt Github

copy

Full Screen

1package com.studio.suku.ngitab.service2import android.util.Log3import androidx.lifecycle.MutableLiveData4import com.github.kittinunf.fuel.Fuel5import com.github.kittinunf.fuel.core.FuelError6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.isSuccessful8import com.github.kittinunf.fuel.gson.responseObject9import com.github.kittinunf.fuel.httpGet10import com.github.kittinunf.result.Result11import com.studio.suku.ngitab.model.ResponseObject12import com.studio.suku.ngitab.utility.Utility13import java.lang.AssertionError14class ApiRepository(){15 private lateinit var placesDataRequest : Request16 fun getListPlaces(onSuccess: (List<ResponseObject>) -> Unit, onError:(FuelError) -> Unit){17 Log.d("Suku", "Doing Request")18 placesDataRequest = Fuel.get(Utility.url).responseObject<List<ResponseObject>>{req, res, result ->19 result.fold({20 onSuccess(it)21 }, {22 onError(it)23 })24 }25 }26}...

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