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

Best Fuel code snippet using com.github.kittinunf.fuel.coroutines.private.awaitObject

LcService.kt

Source:LcService.kt Github

copy

Full Screen

1import com.github.kittinunf.fuel.core.Request2import com.github.kittinunf.fuel.coroutines.awaitObject3import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult4import com.github.kittinunf.fuel.gson.jsonBody5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.json.jsonDeserializer8import org.json.JSONArray9import org.json.JSONObject10object LcService {11 private fun Request.wrapRequest(): Request {12 return request.header("Origin", "https://leetcode-cn.com")13 .header(14 "User-Agent",15 "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"16 )17 }18 private suspend fun token(title: String): String {19 val page = "https://leetcode-cn.com/problems/$title/"20 val (_, response, _) = page.httpGet()21 .wrapRequest()22 .awaitStringResponseResult()23 val cookie = response.header("Set-Cookie").first()24 return "csrftoken=(\\w+);".toRegex().find(cookie)?.groupValues?.getOrNull(1)25 ?: throw IllegalStateException("get token failed")26 }27 private suspend fun problem(frontId: String, title: String, ac: Float): Problem {28 val token = token(title)29 return "https://leetcode-cn.com/graphql".httpPost()30 .wrapRequest()31 .header("Referer", "https://leetcode-cn.com/problems/$title/")32 .header("x-csrftoken", token)33 .header("Cookie", "csrftoken=$token;")34 .jsonBody(ProblemGraphQuery(title))35// .also { println(it) }36 .awaitObject(jsonDeserializer())37 .obj()38 .let {39 val q = it.optJSONObject("data")?.optJSONObject("question")40 ?: throw IllegalArgumentException("invalid problem")41 Problem(42 frontId,43 q.optString("questionTitle"),44 q.optString("questionTitleSlug"),45 q.optString("content"),46 q.optString("difficulty"),47 q.optString("codeDefinition"),48 q.optString("sampleTestCase"),49 ac50 )51 }52 }53 suspend fun allProblems(): JSONArray {54 return "https://leetcode-cn.com/api/problems/all/".httpGet()55 .wrapRequest()56 .awaitObject(jsonDeserializer())57 .obj()58 .getJSONArray("stat_status_pairs")59 }60 suspend fun problemById(id: String): Problem {61 val (frontId, titleSlug, ac) =62 allProblems()63 .map {64 (it as JSONObject).getJSONObject("stat")65 .run {66 Triple(67 getInt("frontend_question_id").toString(),68 optString("question__title_slug"),69 runCatching { optInt("total_acs") * 100F / optInt("total_submitted") }.getOrDefault(0F)70 )...

Full Screen

Full Screen

FBoerseRepoImpl.kt

Source:FBoerseRepoImpl.kt Github

copy

Full Screen

1package com.funglejunk.stockz.repo.fboerse2import com.funglejunk.stockz.data.fboerse.FBoerseHistoryData3import com.funglejunk.stockz.data.fboerse.FBoersePerfData4import com.github.kittinunf.fuel.coroutines.awaitObject5import com.github.kittinunf.fuel.coroutines.awaitObjectResult6import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf9import kotlinx.serialization.UnstableDefault10import kotlinx.serialization.json.Json11import timber.log.Timber12import java.time.LocalDate13@UnstableDefault14class FBoerseRepoImpl : FBoerseRepo {15 private companion object {16 const val BASE_URL = "https://api.boerse-frankfurt.de/data"17 const val PRICE_HISTORY_EP = "/price_history"18 const val PERFORMANCE_EP = "/performance"19 const val ISIN_PARAM_ID = "isin"20 const val MIN_DATE_ID = "minDate"21 const val MAX_DATE_ID = "maxDate"22 val OFFSET_PARAM = "offset" to 023 val LIMIT_PARAM = "limit" to 50524 val MIC_PARAM = "mic" to "XETR"25 }26 override suspend fun getHistory(27 isin: String,28 minDate: LocalDate,29 maxDate: LocalDate30 ): FBoerseHistoryData = (BASE_URL + PRICE_HISTORY_EP).httpGet(31 listOf(32 OFFSET_PARAM,33 LIMIT_PARAM,34 MIC_PARAM,35 ISIN_PARAM_ID to isin,36 MIN_DATE_ID to minDate,37 MAX_DATE_ID to maxDate38 )39 ).awaitObject(kotlinxDeserializerOf(FBoerseHistoryData.serializer()))40 override suspend fun getHistoryPerfData(isin: String): FBoersePerfData =41 (BASE_URL + PERFORMANCE_EP).httpGet(42 listOf(43 MIC_PARAM,44 ISIN_PARAM_ID to isin45 )46 ).awaitObject(kotlinxDeserializerOf(FBoersePerfData.serializer()))47/*48All endpoints reverse engineered49https://api.boerse-frankfurt.de/data/bid_ask_overview?isin=IE00BKX55T58&mic=XETR50https://api.boerse-frankfurt.de/data/price_information?isin=DE0008469008&mic=XETR51https://api.boerse-frankfurt.de/data/quote_box?isin=IE00BKX55T58&mic=XETR *52https://api.boerse-frankfurt.de/data/xetra_trading_parameter?isin=IE00BKX55T5853https://api.boerse-frankfurt.de/data/performance?isin=IE00BKX55T58&mic=XETR *54https://api.boerse-frankfurt.de/data/etp_master_data?isin=IE00BKX55T5855https://api.boerse-frankfurt.de/data/asset_under_management?isin=IE00BKX55T5856https://api.boerse-frankfurt.de/data/investment_focus?isin=IE00BKX55T5857https://api.boerse-frankfurt.de/data/fees_etp?isin=IE00BKX55T5858https://api.boerse-frankfurt.de/data/benchmark?isin=IE00BKX55T5859https://api.boerse-frankfurt.de/data/data_sheet_header?isin=IE00BKX55T5860https://api.boerse-frankfurt.de/data/instrument_information?slug=ishares-msci-em-latin-america-ucits-etf-usd-dist&instrumentType=ETP...

Full Screen

Full Screen

App.kt

Source:App.kt Github

copy

Full Screen

2 * This Kotlin source file was generated by the Gradle 'init' task.3 */4package Producer5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.coroutines.awaitObject7import com.github.kittinunf.fuel.coroutines.awaitUnit8import com.github.kittinunf.fuel.jackson.objectBody9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.delay11import kotlinx.coroutines.launch12import kotlinx.coroutines.runBlocking13import kotlin.random.Random14import kotlin.random.nextInt15import kotlin.time.DurationUnit16import kotlin.time.toDuration17class MainProducer(private val numberOfPoint: Int,) {18 private suspend fun fetchStations(): List<WeatherStationDTO> {19 val data = Fuel.get("http://localhost:8080/stations").awaitObject(WeatherStationDTODeserializer)20 println("Fetched ${data.size} stations")21 return data22 }23 fun start() {24 runBlocking(Dispatchers.Default) {25 println("Starting producer, getting stations lists ....")26 fetchStations().forEach {27 launch {28 println("Starting producer for station ${it.name}")29 StationProducer(it.id).generateWeatherPoints(numberOfPoint)30 }31 }32 }33 }...

Full Screen

Full Screen

AccountsHelper.kt

Source:AccountsHelper.kt Github

copy

Full Screen

...6import com.dproductions.sob.structures.consents.Consent7import com.dproductions.sob.structures.credentials.OauthCredentials8import com.github.kittinunf.fuel.core.FuelError9import com.github.kittinunf.fuel.core.HttpException10import com.github.kittinunf.fuel.coroutines.awaitObject11import com.github.kittinunf.fuel.httpGet12import io.mikael.urlbuilder.UrlBuilder13class AccountsHelper(private val oauthCredentials: OauthCredentials, private val consent: Consent, private val bic: SwedbankBic, isProduction: Boolean) : ApiHelper(isProduction) {14 override val endpoint = getAccountsHelperEndpoint()15 suspend fun getAccounts(): Array<Account> {16 val url = UrlBuilder17 .fromString(endpoint)18 .addParameter("bic", bic.value)19 val accounts: Array<Account>20 try {21 accounts = url.toString()22 .httpGet()23 .header(getAuthenticatedHeaders(oauthCredentials, consent))24 .awaitObject(Account.ObjectDeserializer())25 } catch (exception: Exception) {26 throw getException(exception)27 }28 return accounts29 }30 suspend fun getAccountBalances(accountId: String): AccountBalances {31 val url = UrlBuilder32 .fromString("$endpoint/$accountId/balances")33 .addParameter("bic", bic.value)34 val balanceList: AccountBalances35 try {36 balanceList = url.toString()37 .httpGet()38 .header(getAuthenticatedHeaders(oauthCredentials, consent))39 .awaitObject(AccountBalances.Deserializer())40 } catch (exception: Exception) {41 throw getException(exception)42 }43 return balanceList44 }45 private fun getException(exception: Exception): AccountsException {46 return when (exception){47 is HttpException -> AccountsException(exception.message)48 is FuelError -> AccountsException(exception.message)49 else -> throw AccountsException("Generic exception received with message: ${exception.message}")50 }51 }52}...

Full Screen

Full Screen

RestCoFuel.kt

Source:RestCoFuel.kt Github

copy

Full Screen

1package coroutines2import Post3import com.github.kittinunf.fuel.Fuel4import com.github.kittinunf.fuel.core.ResponseDeserializable5import com.github.kittinunf.fuel.coroutines.awaitObject6import com.github.kittinunf.fuel.coroutines.awaitString7import com.google.gson.Gson8import com.google.gson.reflect.TypeToken9import kotlinx.coroutines.runBlocking10private val home = "https://jsonplaceholder.typicode.com/"11class PostDeserializer : ResponseDeserializable<Post> {12 override fun deserialize(content: String): Post =13 Gson().fromJson(content, Post::class.java)14}15class PostListDeserializer : ResponseDeserializable<List<Post>> {16 override fun deserialize(content: String): List<Post> {17 // https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type18 val listType = object : TypeToken<List<Post>>() {}.type19// val listType = TypeToken.getParameterized(List::class.java, Post::class.java).type20 return Gson().fromJson(content, listType)21 }22}23suspend fun getPostAsString2(): String =24 Fuel.get("${home}posts/1").awaitString()25suspend fun getPostAsJson2(): Post =26 Fuel.get("${home}posts/1").awaitObject(PostDeserializer())27suspend fun getPosts2(n: Int): List<Post> =28 Fuel.get("${home}posts").awaitObject(PostListDeserializer()).take(n)29suspend fun createPost2(): Post =30 Fuel.post("${home}posts", listOf("userId" to 101, "title" to "test title", "body" to "test body"))31 .awaitObject(PostDeserializer())32suspend fun updatePost2(): Post =33 Fuel.put("${home}posts/1", listOf("userId" to 101, "id" to 1, "title" to "test title", "body" to "test body"))34 .awaitObject(PostDeserializer())35suspend fun deletePost2(): String =36 Fuel.delete("${home}posts/1").awaitString()37fun main(args: Array<String>) = runBlocking {38 println(getPostAsString2())39 println(getPostAsJson2())40 println(getPosts2(2))41 println(createPost2())42 println(updatePost2())43 println(deletePost2())44}...

Full Screen

Full Screen

ConsentsHelper.kt

Source:ConsentsHelper.kt Github

copy

Full Screen

...5import com.dproductions.sob.structures.consents.CreateConsentRequest6import com.dproductions.sob.structures.credentials.OauthCredentials7import com.github.kittinunf.fuel.core.FuelError8import com.github.kittinunf.fuel.core.HttpException9import com.github.kittinunf.fuel.coroutines.awaitObject10import com.github.kittinunf.fuel.httpPost11import com.google.gson.Gson12import io.mikael.urlbuilder.UrlBuilder13import java.util.*14class ConsentsHelper(private val oauthCredentials: OauthCredentials, private val bic: SwedbankBic, isProduction: Boolean) : ApiHelper(isProduction) {15 override val endpoint = getConsentsHelperEndpoint()16 suspend fun createConsent(createConsentRequest: CreateConsentRequest): Consent {17 val url = UrlBuilder18 .fromString(endpoint)19 .addParameter("bic", bic.value)20 val consent: Consent21 try {22 consent = url.toString()23 .httpPost()24 .body(Gson().toJson(createConsentRequest))25 .header("Content-Type", "application/json")26 .header("Authorization", "Bearer ${oauthCredentials.accessToken}")27 .header("X-Request-ID", UUID.randomUUID().toString())28 .header("Date", Date().toString())29 .awaitObject(Consent.Deserializer())30 } catch (exception: Exception) {31 when (exception){32 is HttpException -> throw ConsentsException(exception.message)33 is FuelError -> throw ConsentsException(exception.message)34 else -> throw ConsentsException("Generic exception received with message: ${exception.message}")35 }36 }37 return consent38 }39}...

Full Screen

Full Screen

Repositories.kt

Source:Repositories.kt Github

copy

Full Screen

1package se.svt.radio.data2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.coroutines.awaitObject4import org.springframework.stereotype.Repository5import se.svt.radio.domain.*6@Repository7class SRBroadcasts : BroadcastRepository {8 override suspend fun getRecent(programName: ProgramName): List<Broadcast> {9 val programId = getProgramId(programName)10 val broadcastsUrl = "https://api.sr.se/api/v2/broadcasts?programid=$programId&sort=-broadcastdateutc&format=json&size=5"11 val response = Fuel.get(broadcastsUrl).awaitObject(BroadcastResponseDeserializer)12 return response.broadcasts.map { it.toModel() }13 }14 private suspend fun getProgramId(programName: ProgramName): Int {15 val programsUrl = "https://api.sr.se/api/v2/programs?format=json&pagination=false"16 val response = Fuel.get(programsUrl).awaitObject(ProgramResponseDeserializer)17 return response.programs.singleOrNull{it.name.lowercase() == programName.toString().lowercase()}?.id18 ?: throw ProgramNotFound()19 }20}...

Full Screen

Full Screen

ImgurApi.kt

Source:ImgurApi.kt Github

copy

Full Screen

1package com.rpenates.imgurtestlab.network.api2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.coroutines.awaitObject4import com.rpenates.imgurtestlab.data.models.Photo5import com.rpenates.imgurtestlab.network.Routes6import com.rpenates.imgurtestlab.network.helpers.PhotoHelper7class ImgurApi {8 suspend fun queryPhotos(stringQuery: String): List<Photo> =9 Fuel.get("${Routes.galleryRoute}/search/top/all/01?q=${stringQuery}&q_type=jpg")10 .header(Routes.imgurHeaders)11 .also { println(it) }12 .awaitObject(PhotoHelper.PhotoDeserializer)13 companion object {14 @Volatile15 private var instance: ImgurApi? = null16 fun getInstance() =17 instance ?: synchronized(this) {18 instance ?: ImgurApi().also { instance = it }19 }20 }21}

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