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

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

ObjectTest.kt

Source:ObjectTest.kt Github

copy

Full Screen

...54 val data = mocked401().awaitObject(UUIDResponseDeserializer)55 fail("Expected error, actual data $data")56 }57 @Test58 fun awaitObjectResponse() = runBlocking {59 try {60 val (request, response, data) = randomUuid().awaitObjectResponse(UUIDResponseDeserializer)61 assertThat(request, notNullValue())62 assertThat(response, notNullValue())63 assertThat(data, notNullValue())64 } catch (exception: Exception) {65 fail("Expected pass, actual error $exception")66 }67 }68 @Test(expected = FuelError::class)69 fun awaitObjectResponseThrows() = runBlocking {70 val (_, _, data) = mocked401().awaitObjectResponse(UUIDResponseDeserializer)71 fail("Expected error, actual data $data")72 }73 @Test74 fun awaitObjectResult() = runBlocking {75 val (data, error) = randomUuid().awaitObjectResult(UUIDResponseDeserializer)76 assertThat(data, notNullValue())77 }78 @Test79 fun awaitObjectResultFailure() = runBlocking {80 val (data, error) = mocked401().awaitObjectResult(UUIDResponseDeserializer)81 assertThat(error, notNullValue())82 }83 @Test84 fun awaitObjectResponseResult() = runBlocking {85 val (request, response, result) = randomUuid().awaitObjectResponseResult(UUIDResponseDeserializer)86 val (data, error) = result87 assertThat(data, notNullValue())88 assertThat(request, notNullValue())89 assertThat(response, notNullValue())90 }91 @Test92 fun awaitObjectResponseResultFailure() = runBlocking {93 val (data, response, result) = mocked401().awaitObjectResponseResult(UUIDResponseDeserializer)94 assertThat(data, notNullValue())95 assertThat(response, notNullValue())96 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_UNAUTHORIZED))97 assertThat(response.isSuccessful, equalTo(false))98 assertThat(response.headers["foo"], equalTo(listOf("bar") as Collection<String>))99 val (_, error) = result100 assertThat(error!!.response, equalTo(response))101 assertThat(error.response.statusCode, equalTo(response.statusCode))102 assertThat(error.response.body(), equalTo(response.body()))103 }104 @Test105 fun awaitUnit() = runBlocking {106 runCatching {107 val data = randomUuid().awaitUnit()108 assertThat(data, notNullValue())109 assertThat(data, equalTo(Unit))110 }.getOrElse {111 fail("Expected pass, actual error $it")112 }113 }114 @Test115 fun captureDeserializationException() = runBlocking {116 val (request, response, result) = reflectedRequest(Method.GET, "reflected")117 .awaitObjectResponseResult(object : ResponseDeserializable<Unit> {118 override fun deserialize(content: String): Unit? {119 throw IllegalStateException("some deserialization exception")120 }121 })122 val (_, error) = result123 assertThat(error, notNullValue())124 assertThat(response, notNullValue())125 assertThat(request, notNullValue())126 assertThat(response.statusCode, equalTo(200))127 assertThat(response.responseMessage, equalTo("OK"))128 assertThat(error, isA(FuelError::class.java))129 assertThat((error as FuelError).exception as? IllegalStateException, isA(IllegalStateException::class.java))130 }131}...

Full Screen

Full Screen

ApiHandler.kt

Source:ApiHandler.kt Github

copy

Full Screen

1package no.uio.g19.klesapp.data.api2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.Headers4import com.github.kittinunf.fuel.coroutines.awaitObjectResponse5import no.uio.g19.klesapp.BuildConfig.MAPS_API_KEY6import no.uio.g19.klesapp.data.model.geocoder.GeocoderAddress7import no.uio.g19.klesapp.data.model.locationforecast.Locationforecast8import no.uio.g19.klesapp.data.model.nowcast.Nowcast9import no.uio.g19.klesapp.data.model.sunrise.Sunrise10/**11 * An implementation of the ApiInterface12 *13 * Documentation by Metereologisk institutt: in2000.met.no14 *15 * @see ApiInterface16 *17 * @property endpointNowcast Defines the target of the [Nowcast]-API calls18 * @property endpointLocationforecast Defines the target of the [Locationforecast]-API calls19 * @property endpointSunrise Defines the target of the [Sunrise]-API calls20 * @property endpointGeocoderAPI Defines the target of the Geocoder-API calls21 * @property header User-agent to allow the server to recognise and aggregate the apps API calls22 */23class ApiHandler : ApiInterface {24 private val endpointNowcast = "https://in2000-apiproxy.ifi.uio.no/weatherapi/nowcast/2.0/complete?"25 private val endpointLocationforecast = "https://in2000-apiproxy.ifi.uio.no/weatherapi/locationforecast/2.0/complete?"26 private val endpointSunrise = "https://in2000-apiproxy.ifi.uio.no/weatherapi/sunrise/2.0/.json?"27 private val endpointGeocoderAPI = "https://maps.googleapis.com/maps/api/geocode/json?"28 private val header = "no.uio.g19.klesapp/1.0.0"29 /**30 * Fetches a Nowcast-response and returns a parsed version31 *32 * Uses a Deserializer defined in the [Nowcast]-dataclass to parse the JSON-response.33 *34 * @param lat target latitude for the forecast35 * @param lon target longitude for the forecast36 *37 * @return Parsed Nowcast-object38 */39 override suspend fun getNowcast(lat: Float, lon: Float): Nowcast =40 Fuel.get(endpointNowcast, listOf("lat" to lat.toString(), "lon" to lon.toString()))41 .appendHeader(Pair(Headers.USER_AGENT, header))42 .awaitObjectResponse(Nowcast.Deserializer())43 .third44 /**45 * Fetches a Locationforecast-response and returns a parsed version46 *47 * Uses a Deserializer defined in the [Locationforecast]-dataclass to parse the JSON-response.48 *49 * @param lat target latitude for the forecast50 * @param lon target longitude for the forecast51 *52 * @return Parsed Locationforecast-object53 */54 override suspend fun getLocationforecast(lat: Float, lon: Float): Locationforecast =55 Fuel.get(endpointLocationforecast, listOf("lat" to lat.toString(), "lon" to lon.toString()))56 .appendHeader(Pair(Headers.USER_AGENT, header))57 .awaitObjectResponse(Locationforecast.Deserializer())58 .third59 /**60 * Fetches a Sunrise-response and returns a parsed version61 *62 * Uses a Deserializer defined in the [Sunrise]-dataclass to parse the JSON-response.63 *64 * @param lat target latitude for the forecast65 * @param lon target longitude for the forecast66 *67 * @return Parsed Sunrise-object68 */69 override suspend fun getSunrise(lat: Float, lon: Float, date: String, offset: String): Sunrise =70 Fuel.get(endpointSunrise, listOf("lat" to lat.toString(), "lon" to lon.toString(), "date" to date, "offset" to offset))71 .appendHeader(Pair(Headers.USER_AGENT, header))72 .awaitObjectResponse(Sunrise.Deserializer())73 .third74 /**75 * Fetches a Geocoder-response and returns a parsed version76 *77 * Uses a Deserializer defined in the [GeocoderAddress]-dataclass to parse the JSON-response.78 *79 * @param lat target latitude for the forecast80 * @param lon target longitude for the forecast81 *82 * @return Parsed GeocoderAddress-object83 */84 override suspend fun getAddress(lat : Double, lon : Double) : GeocoderAddress =85 Fuel.get(endpointGeocoderAPI, listOf("latlng" to "$lat,$lon", "key" to MAPS_API_KEY))86 .appendHeader(Pair(Headers.USER_AGENT, header))87 .awaitObjectResponse(GeocoderAddress.Deserializer())88 .third89}...

Full Screen

Full Screen

WeatherAccuWeatherPortImpl.kt

Source:WeatherAccuWeatherPortImpl.kt Github

copy

Full Screen

...7import com.artemchep.essence.domain.models.*8import com.artemchep.essence.domain.ports.WeatherPort9import com.artemchep.essence_common.BuildConfig10import com.github.kittinunf.fuel.core.Request11import com.github.kittinunf.fuel.coroutines.awaitObjectResponse12import com.github.kittinunf.fuel.httpGet13import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf14import kotlinx.coroutines.Dispatchers15private const val API_KEY = BuildConfig.API_ACCU_WEATHER16private const val ENDPOINT = "http://dataservice.accuweather.com"17/**18 * @author Artem Chepurnoy19 */20class WeatherAccuWeatherPortImpl : WeatherPort {21 override suspend fun getWeather(geolocation: Geolocation): Either<Throwable, Weather> {22 val (current, today) = try {23 val gbean = createGeopositionRequest(geolocation).await<GeopositionBean>()24 val current = createCurrentlyRequest(gbean).await<ForecastCurrentlyBean>()25 val today = createDailyRequest(gbean).await<ForecastDailyBean>()26 .days27 .first()28 current to today29 } catch (e: Throwable) {30 return Either.Left(e)31 }32 return Either.Right(33 Weather(34 current = WeatherCurrent(35 wind = Wind(mps = current.wind.speed.metric.value),36 temp = Temperature(c = current.temp.metric.value)37 ),38 today = WeatherToday(39 tempMax = Temperature(c = today.temp.max.value),40 tempMin = Temperature(c = today.temp.min.value)41 )42 )43 )44 }45 private fun createGeopositionRequest(geolocation: Geolocation) =46 "$ENDPOINT/locations/v1/cities/geolocation/search"47 .httpGet(48 listOf(49 "apikey" to API_KEY,50 "q" to "${geolocation.latitude},${geolocation.longitude}"51 )52 )53 private fun createDailyRequest(gbean: GeopositionBean) =54 "$ENDPOINT/forecasts/v1/daily/1day/${gbean.key}"55 .httpGet(56 listOf(57 "apikey" to API_KEY,58 "metric" to true59 )60 )61 private fun createCurrentlyRequest(gbean: GeopositionBean) =62 "$ENDPOINT/currentconditions/v1/${gbean.key}"63 .httpGet(64 listOf(65 "apikey" to API_KEY,66 "details" to true67 )68 )69 private suspend inline fun <reified T : Any> Request.await() =70 awaitObjectResponse<T>(71 kotlinxDeserializerOf(json),72 Dispatchers.IO73 ).third74}...

Full Screen

Full Screen

MainActivity.kt

Source:MainActivity.kt Github

copy

Full Screen

1package com.example.lynas.myapplication2import android.os.Bundle3import android.support.v7.app.AppCompatActivity4import android.widget.TextView5import awaitObjectResponse6import com.github.kittinunf.fuel.Fuel7import com.github.kittinunf.fuel.gson.gsonDeserializerOf8import com.google.gson.Gson9import kotlinx.coroutines.experimental.android.UI10import kotlinx.coroutines.experimental.async11import org.jetbrains.anko.button12import org.jetbrains.anko.sdk25.coroutines.onClick13import org.jetbrains.anko.textView14import org.jetbrains.anko.verticalLayout15class MainActivity : AppCompatActivity() {16 private lateinit var textView: TextView17 override fun onCreate(savedInstanceState: Bundle?) {18 super.onCreate(savedInstanceState)19// setContentView(R.layout.activity_main)20 verticalLayout {21 button {22 text = "Get List"23 }.onClick {24 getPersonList()25 }26 button {27 text = "Get One"28 }.onClick {29 getPerson()30 }31 button {32 text = "Post"33 }.onClick {34 postPerson()35 }36 textView = textView {37 text = "Hello world"38 }39 }40 }41 private fun getPersonList() {42 async(UI) {43 val (request, response, result) = Fuel.get("http://192.168.1.2:8080/persons")44 .awaitObjectResponse(gsonDeserializerOf<List<Person>>())45 result.fold({ data ->46 textView.text = "${data}"47 }, { error ->48 textView.text = error.localizedMessage49 })50 }51 }52 private fun getPerson() {53 async(UI) {54 val (request, response, result) = Fuel.get("http://192.168.1.2:8080/persons/1")55 .awaitObjectResponse(gsonDeserializerOf<Person>())56 result.fold({ data ->57 textView.text = "${data}"58 }, { error ->59 textView.text = error.localizedMessage60 })61 }62 }63 private fun postPerson() {64 val header = mapOf("Content-Type" to "application/json")65 async(UI) {66 val (request, response, result) = Fuel.post("http://192.168.1.2:8080/persons")67 .header(header)68 .body(Gson().toJson(Person(6,"Flame",66)))69 .awaitObjectResponse(gsonDeserializerOf<Person>())70 result.fold({ data ->71 textView.text = "${data}"72 }, { error ->73 textView.text = error.localizedMessage74 })75 }76 }77}78data class Person(val id:Int, val name:String, val age:Int)...

Full Screen

Full Screen

WeatherDarkSkyPortImpl.kt

Source:WeatherDarkSkyPortImpl.kt Github

copy

Full Screen

...5import com.artemchep.essence.domain.models.*6import com.artemchep.essence.domain.ports.WeatherPort7import com.artemchep.essence_common.BuildConfig8import com.github.kittinunf.fuel.core.Request9import com.github.kittinunf.fuel.coroutines.awaitObjectResponse10import com.github.kittinunf.fuel.httpGet11import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf12import kotlinx.coroutines.Dispatchers13private const val API_KEY = BuildConfig.API_DARK_SKY14/**15 * @author Artem Chepurnoy16 */17class WeatherDarkSkyPortImpl : WeatherPort {18 override suspend fun getWeather(geolocation: Geolocation): Either<Throwable, Weather> {19 val forecast = try {20 createRequest(geolocation).await<ForecastBean>()21 } catch (e: Throwable) {22 return Either.Left(e)23 }24 // Convert the bean to the common weather25 // model.26 val current = forecast.currently27 val today = forecast.daily.days.first()28 return Either.Right(29 Weather(30 current = WeatherCurrent(31 wind = Wind(mps = current.wind),32 temp = Temperature(c = current.temp)33 ),34 today = WeatherToday(35 tempMax = Temperature(c = today.tempMax),36 tempMin = Temperature(c = today.tempMin)37 )38 )39 )40 }41 private fun createRequest(geolocation: Geolocation) =42 "https://api.darksky.net/forecast/$API_KEY/${geolocation.latitude},${geolocation.longitude}"43 .httpGet(44 listOf(45 "units" to "si"46 )47 )48 private suspend inline fun <reified T : Any> Request.await() =49 awaitObjectResponse<T>(50 kotlinxDeserializerOf(json),51 Dispatchers.IO52 ).third53}...

Full Screen

Full Screen

WeatherOpenWeatherMapPortImpl.kt

Source:WeatherOpenWeatherMapPortImpl.kt Github

copy

Full Screen

...5import com.artemchep.essence.domain.models.*6import com.artemchep.essence.domain.ports.WeatherPort7import com.artemchep.essence_common.BuildConfig8import com.github.kittinunf.fuel.core.Request9import com.github.kittinunf.fuel.coroutines.awaitObjectResponse10import com.github.kittinunf.fuel.httpGet11import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf12import kotlinx.coroutines.Dispatchers13private const val API_KEY = BuildConfig.API_OPEN_WEATHER_MAP14private const val ENDPOINT = "https://api.openweathermap.org"15/**16 * @author Artem Chepurnoy17 */18class WeatherOpenWeatherMapPortImpl : WeatherPort {19 override suspend fun getWeather(geolocation: Geolocation): Either<Throwable, Weather> {20 val forecast = try {21 createRequest(geolocation).await<ForecastBean>()22 } catch (e: Throwable) {23 return Either.Left(e)24 }25 // Convert the bean to the common weather26 // model.27 return Either.Right(28 Weather(29 current = WeatherCurrent(30 wind = Wind(mps = forecast.wind.speed),31 temp = Temperature(c = forecast.main.temp)32 ),33 today = null34 )35 )36 }37 private fun createRequest(geolocation: Geolocation) =38 "$ENDPOINT/data/2.5/weather"39 .httpGet(40 listOf(41 "appid" to API_KEY,42 "lat" to geolocation.latitude,43 "lon" to geolocation.longitude,44 "units" to "metric"45 )46 )47 private suspend inline fun <reified T : Any> Request.await() =48 awaitObjectResponse<T>(49 kotlinxDeserializerOf(json),50 Dispatchers.IO51 ).third52}

Full Screen

Full Screen

WeatherWeatherStackPortImpl.kt

Source:WeatherWeatherStackPortImpl.kt Github

copy

Full Screen

...5import com.artemchep.essence.domain.models.*6import com.artemchep.essence.domain.ports.WeatherPort7import com.artemchep.essence_common.BuildConfig8import com.github.kittinunf.fuel.core.Request9import com.github.kittinunf.fuel.coroutines.awaitObjectResponse10import com.github.kittinunf.fuel.httpGet11import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf12import kotlinx.coroutines.Dispatchers13private const val API_KEY = BuildConfig.API_WEATHER_STACK14private const val ENDPOINT = "http://api.weatherstack.com"15/**16 * @author Artem Chepurnoy17 */18class WeatherWeatherStackPortImpl : WeatherPort {19 override suspend fun getWeather(geolocation: Geolocation): Either<Throwable, Weather> {20 val forecast = try {21 createRequest(geolocation).await<ForecastBean>()22 } catch (e: Throwable) {23 return Either.Left(e)24 }25 // Convert the bean to the common weather26 // model.27 return Either.Right(28 Weather(29 current = WeatherCurrent(30 wind = Wind(mps = forecast.current.wind),31 temp = Temperature(c = forecast.current.temp)32 ),33 today = null34 )35 )36 }37 private fun createRequest(geolocation: Geolocation) =38 "$ENDPOINT/current"39 .httpGet(40 listOf(41 "access_key" to API_KEY,42 "query" to "${geolocation.latitude},${geolocation.longitude}",43 "units" to "m"44 )45 )46 private suspend inline fun <reified T : Any> Request.await() =47 awaitObjectResponse<T>(48 kotlinxDeserializerOf(json),49 Dispatchers.IO50 ).third51}

Full Screen

Full Screen

OppslagClient.kt

Source:OppslagClient.kt Github

copy

Full Screen

1package no.nav.hjelpemidler.soknad.mottak.metrics.kommune2import com.fasterxml.jackson.module.kotlin.readValue3import com.github.kittinunf.fuel.core.ResponseDeserializable4import com.github.kittinunf.fuel.coroutines.awaitObjectResponse5import com.github.kittinunf.fuel.httpGet6import no.nav.hjelpemidler.soknad.mottak.Configuration7import no.nav.hjelpemidler.soknad.mottak.JacksonMapper8import org.slf4j.LoggerFactory9import java.util.UUID10class OppslagClient(11 private val oppslagUrl: String = Configuration.oppslagUrl12) {13 suspend fun hentAlleKommuner(): Map<String, KommuneDto> {14 val kommunenrUrl = "$oppslagUrl/geografi/kommunenr"15 LOG.info("Henter alle kommuner fra $kommunenrUrl")16 try {17 return kommunenrUrl.httpGet()18 .header(19 mapOf(20 "Accept" to "application/json",21 "X-Correlation-ID" to UUID.randomUUID().toString()22 )23 )24 .awaitObjectResponse(25 object : ResponseDeserializable<Map<String, KommuneDto>> {26 override fun deserialize(content: String): Map<String, KommuneDto> {27 return JacksonMapper.objectMapper.readValue(content)28 }29 }30 ).third31 } catch (e: Exception) {32 LOG.error("Henting av kommune feilet", e)33 throw e34 }35 }36 companion object {37 private val LOG = LoggerFactory.getLogger(OppslagClient::class.java)38 }...

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