Best Fuel code snippet using com.github.kittinunf.fuel.coroutines.private.awaitUnit
Deserializable.kt
Source:Deserializable.kt
...221 *222 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]223 * to a large file without using response result224 *225 * To run method in different coroutine context, use `com.github.kittinunf.fuel.coroutines.awaitUnit` in `fuel-coroutines` module226 */227@Throws(FuelError::class)228suspend fun Request.awaitUnit(): Unit = await(EmptyDeserializer)229/**230 * Await [T] or [FuelError]231 * @return [ResponseOf<T>] the [Result] of [T]232 */233@Throws(FuelError::class)234suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponse(deserializable: U): ResponseOf<T> {235 val response = suspendable().await()236 return runCatching { Triple(this, response, deserializable.deserialize(response)) }237 .onFailure { throw FuelError.wrap(it, response) }238 .getOrThrow()239}240/**241 * Await [T] or [FuelError]242 * @return [Result<T>] the [Result] of [T]...
JenkinsUpdateTask.kt
Source:JenkinsUpdateTask.kt
...33import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule34import com.fasterxml.jackson.module.kotlin.registerKotlinModule35import com.github.kittinunf.fuel.core.FuelManager36import com.github.kittinunf.fuel.core.Request37import com.github.kittinunf.fuel.core.awaitUnit38import com.github.kittinunf.fuel.coroutines.awaitObject39import com.github.kittinunf.fuel.jackson.jacksonDeserializerOf40import java.io.File41import java.time.Instant42import org.slf4j.kotlin.debug43import org.slf4j.kotlin.getLogger44import org.slf4j.kotlin.info45import kotlin.math.ln46import kotlin.math.pow47class JenkinsUpdateTask(48 jenkinsUrl: String = "https://ci.solo-studios.ca",49 jenkinsProject: String = "job/solo-studios/job/PolyBot",50 ) : UpdateTask {51 private val logger by getLogger()52 53 private val baseUrl = "$jenkinsUrl/$jenkinsProject"54 55 private val fuel = FuelManager().also {56 it.basePath = baseUrl57 }58 private val mapper = ObjectMapper().registerKotlinModule().also {59 it.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)60 it.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, true)61 it.registerModule(JavaTimeModule())62 }63 64 override suspend fun update(file: File) {65 logger.info { "Downloading the latest jar from Jenkins." }66 logger.debug { "Querying Jenkins at url $baseUrl for the latest successful build." }67 val build = fuel.get("${lastSuccessfulBuildUrl}/${jsonApiUrl}")68 .awaitObject<JenkinsBuild>(mapper)69 70 val artifact = build.artifacts.find { it.fileName.endsWith("-all.jar") } ?: error("Could not find an artifact ending in -all.jar.")71 72 logger.debug { "Latest successful build artifact found: ${artifact.fileName}, ${artifact.relativePath}" }73 74 var lastUpdate = 0L75 76 fuel.download("${lastSuccessfulBuildUrl}/$artifactUrl/${artifact.relativePath}")77 .fileDestination { _, _ -> file }78 .progress { readBytes, totalBytes ->79 if (System.currentTimeMillis() - lastUpdate > 100) {80 lastUpdate = System.currentTimeMillis()81 val progress = (readBytes.toDouble() / totalBytes.toDouble()) * 10082 logger.info { "Downloading: [%.2f%%] %s/%s".format(progress, readBytes.humanBytes(), totalBytes.humanBytes()) }83 }84 }.awaitUnit()85 86 logger.debug { "Downloaded the latest jar artifact." }87 }88 89 @JsonIgnoreProperties(ignoreUnknown = true)90 private data class JenkinsBuild(91 val id: Long,92 val fullDisplayName: String,93 val timestamp: Instant,94 val url: String,95 val artifacts: List<JenkinsArtifact>96 )97 98 @JsonIgnoreProperties(ignoreUnknown = true)...
ObjectTest.kt
Source:ObjectTest.kt
...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 })...
LogDownloader.kt
Source:LogDownloader.kt
...5import com.github.ajalt.clikt.parameters.options.option6import com.github.ajalt.clikt.parameters.options.required7import com.github.ajalt.clikt.parameters.types.int8import com.github.ajalt.clikt.parameters.types.path9import com.github.kittinunf.fuel.core.awaitUnit10import com.github.kittinunf.fuel.core.extensions.jsonBody11import com.github.kittinunf.fuel.core.requests.download12import com.github.kittinunf.fuel.httpGet13import com.github.kittinunf.fuel.httpPost14import com.github.kittinunf.fuel.serialization.responseObject15import com.github.kittinunf.result.getOrElse16import kotlinx.coroutines.GlobalScope17import kotlinx.coroutines.launch18import kotlinx.coroutines.runBlocking19import java.io.File20import java.nio.file.Path21import java.text.SimpleDateFormat22import java.util.Date23import java.util.concurrent.atomic.AtomicInteger24import kotlin.system.exitProcess25class LogDownloader : CirrusCommand() {26 val branch: String? by option(27 "-b", "--branch",28 help = "The branch from which to get the logs from. If not provided, quirrus will not filter for branches."29 )30 val numberOfTasks: Int by option(31 "-n", "--number-of-tasks",32 help = "The number of tasks for which to fetch the logs, starting and including the newest task, going backwards in time."33 ).int().default(0)34 val tasks: List<String>? by option(35 "-k", "--tasks",36 help = "A comma-separated list of the name(s) of the task(s) to download logs for. Not providing a value here will attempt to " +37 "download the logs for all tasks."38 ).convert { it.split(",") }39 val taskIds: List<String>? by option(40 "--taskIds",41 help = "A comma-separated list of task IDs of the concrete tasks of which to get the logs."42 ).convert { it.split(",") }43 val logFileName: String by option(44 "-l", "--logfile",45 help = "The name of the log file to download."46 ).required()47 val targetDirectory: Path by argument().path(mustExist = true, canBeFile = false)48 override fun run() {49 val discoveredTasks = getLastNBuilds(numberOfTasks).let { (req, _, result) ->50 result.getOrElse { e ->51 logger.error("Could not fetch last $numberOfTasks builds: $e")52 exitProcess(1)53 }.let { apiResponse ->54 tasks55 apiResponse.data?.repository?.builds?.edges?.flatMap { edge ->56 edge.node.let { buildNode ->57 buildNode.tasks.filter { task ->58 tasks?.contains(task.name) ?: true59 }.map { it to buildNode }60 }61 } ?: run {62 logger.error("Got invalid response while trying to get last $numberOfTasks builds: $apiResponse")63 exitProcess(1)64 }65 }66 }67 runBlocking {68 downloadLogs((taskIds?.map { Task(it, "UNKNOWN", 0) to null } ?: emptyList()) + discoveredTasks)69 }70 }71 fun getLastNBuilds(numberOfBuilds: Int) =72 apiUrl.httpPost()73 .authenticate()74 .let { request ->75 requestTimeout?.let {76 request.timeout(it * 1000)77 request.timeoutRead(it * 1000)78 } ?: request79 }80 .jsonBody(RequestBuilder.tasksQuery(repositoryId, branch, numberOfBuilds).toRequestString())81 .responseObject<RepositoryApiResponse>(json)82 val dateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm")83 private suspend fun downloadLogs(taskIds: List<Pair<Task, BuildNode?>>) {84 var successful = AtomicInteger()85 var failed = AtomicInteger()86 taskIds.map { (task, buildNode) ->87 GlobalScope.launch {88 val destinationPath = if (buildNode != null) {89 val branchEscaped = buildNode.branch.replace(File.separatorChar, '_').replace(File.pathSeparatorChar, '_')90 val buildTime = dateFormat.format(Date(task.creationTimestamp))91 targetDirectory.resolve("${logFileName}_${buildTime}_${branchEscaped}_${task.id}.log")92 } else {93 targetDirectory.resolve("${logFileName}_${task.id}.log")94 }95 val downloadLink = RequestBuilder.logDownloadLink(task.id, logFileName)96 logger.verbose { "Downloading log for task ${task.id} from $downloadLink..." }97 runCatching {98 downloadLink99 .httpGet()100 .authenticate()101 .download()102 .fileDestination { _, _ -> destinationPath.toFile() }103 .awaitUnit()104 }.onFailure { e ->105 failed.incrementAndGet()106 logger.error("Error downloading $destinationPath from '$downloadLink': ${e.localizedMessage}")107 }.onSuccess {108 successful.incrementAndGet()109 logger.print { "Downloaded $destinationPath." }110 }111 }112 }.forEach {113 it.join()114 }115 logger.print { "Downloaded ${successful.get()} successfully, ${failed.get()} failed." }116 }117}...
RemoteRoomsManager.kt
Source:RemoteRoomsManager.kt
...13import com.github.kittinunf.fuel.core.FuelError14import com.github.kittinunf.fuel.core.Request15import com.github.kittinunf.fuel.core.extensions.jsonBody16import com.github.kittinunf.fuel.coroutines.awaitObjectResponseResult17import com.github.kittinunf.fuel.coroutines.awaitUnit18import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf19import kotlinx.serialization.DeserializationStrategy20import kotlinx.serialization.builtins.ListSerializer21import kotlinx.serialization.builtins.serializer22import kotlinx.serialization.encodeToString23import kotlinx.serialization.json.Json24object RemoteRoomsManager {25 suspend fun search(): RemoteResult<List<Room>> =26 catchFuelError { FuelRoomsManager.search() }27 suspend fun create(input: CreateRoomInput): RemoteResult<RoomId> =28 catchFuelError { FuelRoomsManager.create(input) }29 suspend fun join(input: JoinRoomInput): RemoteResult<JoinRoomResult> =30 catchFuelError { FuelRoomsManager.join(input) }31 suspend fun check(input: CheckRoomInput): RemoteResult<CheckRoomResult> =32 catchFuelError { FuelRoomsManager.check(input) }33 suspend fun ready(input: ReadyPlayerInput): RemoteResult<Unit> =34 catchFuelError { FuelRoomsManager.ready(input) }35 suspend fun locations(): RemoteResult<List<GameLocation>> =36 catchFuelError { FuelRoomsManager.locations() }37 private inline fun <T> catchFuelError(call: () -> T): RemoteResult<T> =38 try {39 RemoteResult.Success(call())40 } catch (error: FuelError) {41 RemoteResult.Error42 }43 private object FuelRoomsManager : RoomsManager {44 override suspend fun search(): List<Room> =45 get("/search").await(ListSerializer(Room.serializer()))46 override suspend fun create(input: CreateRoomInput): RoomId =47 post("/create", input).await(RoomId.serializer())48 override suspend fun join(input: JoinRoomInput): JoinRoomResult =49 post("/join", input).await(JoinRoomResult.serializer())50 override suspend fun check(input: CheckRoomInput): CheckRoomResult =51 post("/check", input).await(CheckRoomResult.serializer())52 override suspend fun ready(input: ReadyPlayerInput) =53 post("/ready", input).awaitUnit()54 override suspend fun locations(): List<GameLocation> =55 get("/locations").await(ListSerializer(GameLocation.serializer()))56 private fun get(path: String): Request =57 Fuel.get("$API_HOST$path")58 private inline fun <reified Body> post(path: String, body: Body): Request =59 Fuel.post("$API_HOST$path")60 .jsonBody(Json.encodeToString(body))61 private suspend inline fun <reified T : Any> Request.await(62 deserializationStrategy: DeserializationStrategy<T>63 ): T = awaitObjectResponseResult(kotlinxDeserializerOf(deserializationStrategy))64 .let { (_, _, result) -> result.get() }65 }66 const val API_HOST = "https://api-spyfall.herokuapp.com"67}...
Message.kt
Source:Message.kt
...40 Fuel.post(Email.HTTP + Email.Endpoint.REPLY)41 .body("""{"messageId": $id, "replyBody": $message}""")42 .apply { set("cookie", cookies) }43 .apply { logger.debug { "Sending reply to $sender" } }44 .awaitUnit()45 } catch (e: Exception) {46 logger.error(e) { Email.RESPONSE_EXCEPTION_MSG }47 delay(5_000)48 reply(message)49 }50 }51 /**52 * Forwards this message to sb else53 *54 * @param address email address of person you want to send this message to55 */56 suspend fun forward(address: String) {57 try {58 Fuel.post(Email.HTTP + Email.Endpoint.FORWARD)59 .body("""{ "messageId": $id, "forwardAddress": $address}""")60 .apply { set("cookie", cookies) }61 .apply { logger.debug { "Forwarding message to $address" } }62 .awaitUnit()63 } catch (e: Exception) {64 logger.error(e) { Email.RESPONSE_EXCEPTION_MSG }65 delay(5_000)66 forward(address)67 }68 }69}
App.kt
Source:App.kt
...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 }34}35class StationProducer(private val stationId: String) {36 private val delay = Random.nextInt(100..800).toDuration(DurationUnit.MILLISECONDS)37 private val listWindDirection = listOf(38 "N",39 "NNE",40 "NE",41 "ENE",42 "E",43 "ESE",44 "SE",45 "SSE",46 "S",47 "SSW",48 "SW",49 "WSW",50 "W",51 "WNW",52 "NW",53 "NNW"54 )55 private fun generateWeatherPoint(temp: Double) = WeatherPointDTO(temp, "C", Random.nextInt(1..80).toString() + listWindDirection.random())56 suspend fun generateWeatherPoints(numberOfPoint: Int) {57 var previousTemp = Random.nextDouble(-10.0, 30.0)58 for (i in 1..numberOfPoint) {59 val temp = previousTemp.randomPercent()60 val weatherPoint = generateWeatherPoint(temp)61 println("$i --> $stationId: $weatherPoint")62 sendPoint(weatherPoint)63 previousTemp = temp64 delay(delay)65 }66 }67 private suspend fun sendPoint(weatherPoint: WeatherPointDTO) {68 Fuel.post("http://localhost:8080/stations/$stationId/points")69 .objectBody(weatherPoint)70 .awaitUnit()71 }72}73fun main() {74 MainProducer(100).start()75}...
TvRemote.kt
Source:TvRemote.kt
1package com.pointlessapps.tvremote_client.tv23import android.content.Intent4import android.view.KeyEvent5import com.github.kittinunf.fuel.core.awaitUnit6import com.github.kittinunf.fuel.httpPost7import com.pointlessapps.tvremote_client.models.DeviceWrapper8import com.pointlessapps.tvremote_client.utils.SwipeTouchHandler9import kotlinx.coroutines.delay1011class TvRemote(private val deviceWrapper: DeviceWrapper) {1213 fun sendKeyEvent(keyCode: Int, action: Int) {14 deviceWrapper.device?.sendKeyEvent(keyCode, action)15 }1617 fun sendClick(keyCode: Int) {18 sendKeyEvent(keyCode, KeyEvent.ACTION_DOWN)19 sendKeyEvent(keyCode, KeyEvent.ACTION_UP)20 }2122 suspend fun sendLongClick(keyCode: Int) {23 sendKeyEvent(keyCode, KeyEvent.ACTION_DOWN)24 delay(SwipeTouchHandler.LONG_CLICK_TIME)25 sendKeyEvent(keyCode, KeyEvent.ACTION_UP)26 }2728 fun sendIntent(intent: Intent) {29 deviceWrapper.device?.sendIntent(intent)30 }3132 suspend fun powerOn() {33 runCatching {34 "http://${deviceWrapper.device?.deviceInfo?.uri?.host}:8080/power/on"35 .httpPost().awaitUnit()36 }37 }3839 suspend fun powerOff() {40 runCatching {41 "http://${deviceWrapper.device?.deviceInfo?.uri?.host}:8080/power/off"42 .httpPost().awaitUnit()43 }44 }4546 suspend fun openApp(packageName: String, activityName: String) {47 runCatching {48 "http://${deviceWrapper.device?.deviceInfo?.uri?.host}:8080/open/${packageName}"49 .httpPost().awaitUnit()50 }.onFailure {51 sendIntent(Intent(Intent.ACTION_MAIN).apply {52 setClassName(packageName, activityName)53 })54 }55 }
...
awaitUnit
Using AI Code Generation
1 fun awaitUnit(request: Request): Unit = runBlocking(dispatcher) {2 val (_, _, result) = request.await()3 result.fold({ }, { throw it })4 }5}6private fun main() {7}8 fun awaitUnit(request: Request): Unit = runBlocking(dispatcher) {9 val (_, _, result) = request.await()10 result.fold({ }, { throw it })11 }12}13private fun main() {14}15 fun awaitUnit(request: Request): Unit = runBlocking(dispatcher) {16 val (_, _, result) = request.await()17 result.fold({ }, { throw it })18 }19}20private fun main() {21}22 fun awaitUnit(request: Request): Unit = runBlocking(dispatcher) {23 val (_, _, result) = request.await()24 result.fold({ }, { throw it })25 }26}27private fun main() {28}29 fun awaitUnit(request: Request): Unit = runBlocking(dispatcher) {30 val (_, _, result) = request.await()31 result.fold({ }, { throw it })32 }33}34private fun main() {35}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!