Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.private.failure
Deserializable.kt
Source:Deserializable.kt
...116 *117 * @see ResponseHandler118 *119 * @param deserializable [U] the instance that performs deserialization120 * @param handler [ResponseHandler<T>] handler that has dedicated paths for success and failure121 * @return [CancellableRequest] the request that can be cancelled122 */123fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseHandler<T>): CancellableRequest =124 response(deserializable,125 { request, response, value -> handler.success(request, response, value) },126 { request, response, error -> handler.failure(request, response, error) }127 )128/**129 * Deserialize the [Response] to the [this] into a [T] using [U]130 *131 * @see Handler132 *133 * @param deserializable [U] the instance that performs deserialization134 * @param handler [Handler<T>] handler that has dedicated paths for success and failure135 * @return [CancellableRequest] the request that can be cancelled136 */137fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: Handler<T>): CancellableRequest =138 response(deserializable,139 { _, _, value -> handler.success(value) },140 { _, _, error -> handler.failure(error) }141 )142/**143 * Deserialize the [Response] to the [this] into a [T] using [U]144 *145 * @note not async, use the variations with a handler instead.146 *147 * @throws Exception if there is an internal library error, not related to Network or Deserialization148 *149 * @param deserializable [U] the instance that performs deserialization150 * @return [ResponseResultOf<T>] the response result of151 */152fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U): ResponseResultOf<T> {153 // First execute the network request and catch any issues154 val rawResponse = runCatching { toTask().call() }155 .onFailure { error ->156 FuelError.wrap(error, Response.error(url)).also {157 return Triple(this, it.response, Result.error(it))158 }159 }160 .getOrThrow()161 // By this time it should have a response, but deserialization might fail162 return runCatching { Triple(this, rawResponse, Result.Success(deserializable.deserialize(rawResponse))) }163 .recover { error -> Triple(this, rawResponse, Result.Failure(FuelError.wrap(error, rawResponse))) }164 .getOrThrow()165}166/**167 * Ignore the response result168 *169 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]170 * to a large download and without using the result [ByteArray]171 *172 * @see [com.github.kittinunf.fuel.core.Request.response]173 *174 * @note not async, use the variations with a handler instead.175 *176 * @throws Exception if there is an internal library error, not related to Network177 */178fun Request.responseUnit(): ResponseResultOf<Unit> = response(EmptyDeserializer)179private fun <T : Any, U : Deserializable<T>> Request.response(180 deserializable: U,181 success: (Request, Response, T) -> Unit,182 failure: (Request, Response, FuelError) -> Unit183): CancellableRequest {184 val asyncRequest = RequestTaskCallbacks(185 request = this,186 onSuccess = { response ->187 // The network succeeded but deserialization might fail188 val deliverable = Result.of<T, Exception> { deserializable.deserialize(response) }189 executionOptions.callback {190 deliverable.fold(191 { success(this, response, it) },192 { failure(this, response, FuelError.wrap(it, response).also { error ->193 Fuel.trace { "[Deserializable] unfold failure: \n\r$error" } })194 }195 )196 }197 },198 onFailure = { error, response ->199 executionOptions.callback {200 failure(this, response, error.also { error ->201 Fuel.trace { "[Deserializable] callback failure: \n\r$error" }202 })203 }204 }205 )206 return CancellableRequest.enableFor(this, future = executionOptions.submit(asyncRequest))207}208/**209 * Await [T] or throws [FuelError]210 * @return [T] the [T]211 */212@Throws(FuelError::class)213suspend fun <T : Any, U : Deserializable<T>> Request.await(deserializable: U): T {214 val response = suspendable().await()215 return runCatching { deserializable.deserialize(response) }...
App.kt
Source:App.kt
...80 }81 val (_, response, result) = httpRequest.awaitByteArrayResponseResult()82 result.fold(83 { success -> call.forward(response, success)},84 { failure ->85 if (-1 == response.statusCode) {86 logger.error(failure.toString())87 call.respondErrorAndLog(HttpStatusCode.GatewayTimeout, "Unable to proxy request.")88 } else {89 call.forward(response, failure.errorData)90 }91 }92 )93 }94 }95 }96 }97}98private suspend fun ApplicationCall.forward(99 clientResponse: Response,100 body: ByteArray101) {102 clientResponse.headers.forEach { key, value ->103 if (!HttpHeaders.isUnsafe(key)) {...
CkanDataPublisher.kt
Source:CkanDataPublisher.kt
1package info.hieule.arx_automation.app.springboot.adapter.data_publisher2import com.fasterxml.jackson.databind.ObjectMapper3import com.github.kittinunf.fuel.core.FileDataPart4import com.github.kittinunf.fuel.core.extensions.jsonBody5import com.github.kittinunf.fuel.core.requests.upload6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.result.Result;8import info.hieule.arx_automation.app.springboot.consumer.configuration.CkanConnectorConfiguration9import info.hieule.arx_automation.ports.DataPublisher10import info.hieule.arx_automation.ports.DatasetReader11import info.hieule.arx_automation.shared.models.Dataset12import info.hieule.arx_automation.shared.models.PublicationRequest13import info.hieule.arx_automation.shared.models.PublicationResult14import org.slf4j.LoggerFactory15import java.io.File16import java.io.FileWriter17import java.util.*18class CkanDataPublisher(19 private val objectMapper: ObjectMapper,20 private val datasetReader: DatasetReader,21 private val ckanConnectorConfiguration: CkanConnectorConfiguration22) : DataPublisher {23 private val logger = LoggerFactory.getLogger(CkanDataPublisher::class.java)24 override fun publish(publicationRequest: PublicationRequest): PublicationResult {25 val dataset = this.datasetReader.read()26 val datasetCsvFile = this.createTmpCsv(dataset)27 val datasetName = this.generatePackageName()28 this.createPackage(datasetName, publicationRequest)29 this.logger.info("Created dataset [{}] on CKAN.", datasetName)30 this.uploadResource(datasetName, datasetCsvFile)31 return PublicationResult(32 publicationRequest.requestId,33 "${this.ckanConnectorConfiguration.hostname}/dataset/${datasetName}"34 )35 }36 private fun createTmpCsv(dataset: Dataset): File {37 val file = createTempFile(suffix = ".csv")38 this.logger.info("A temporary dataset is created at [{}]", file.absolutePath)39 val fileWriter = FileWriter(file)40 for (record in dataset.data) {41 fileWriter.append(record.joinToString(","))42 fileWriter.append("\n")43 }44 fileWriter.flush()45 fileWriter.close()46 return file47 }48 private fun generatePackageName(): String {49 return UUID.randomUUID().toString()50 }51 private fun createPackage(packageName: String, publicationRequest: PublicationRequest) {52 val (request, response, result) = "${this.ckanConnectorConfiguration.hostname}/api/action/package_create"53 .httpPost()54 .header("Authorization", this.ckanConnectorConfiguration.apiKey)55 .jsonBody("{\n" +56 " \"name\": \"${packageName}\",\n" +57 " \"title\": \"${publicationRequest.title}\",\n" +58 " \"notes\": \"${publicationRequest.description}\",\n" +59 " \"license_id\": \"${this.ckanConnectorConfiguration.defaultLicense}\",\n" +60 " \"owner_org\": \"${this.ckanConnectorConfiguration.organization}\"\n" +61 "}")62 .responseString()63 when (result) {64 is Result.Success -> {65 return66 }67 is Result.Failure -> {68 throw RuntimeException("Failed to create package")69 }70 }71 }72 private fun uploadResource(packageName: String, csvFile: File) {73 val (request, response, result) = "${this.ckanConnectorConfiguration.hostname}/api/action/resource_create"74 .httpPost(parameters = listOf("package_id" to packageName))75 .header("Authorization", this.ckanConnectorConfiguration.apiKey)76 .upload()77 .add(78 FileDataPart(csvFile, name = "upload")79 )80 .responseString()81 when (result) {82 is Result.Success -> {83 return84 }85 is Result.Failure -> {86 throw RuntimeException("Failed to create package")87 }88 }89 }90}...
SuspendableRequest.kt
Source:SuspendableRequest.kt
...41 }42 .getOrThrow()43 }44 .onFailure { error ->45 Fuel.trace { "[RequestTask] on failure ${(error as? FuelError)?.exception ?: error}" }46 if (error is FuelError && error.causedByInterruption) {47 Fuel.trace { "[RequestTask] execution error\n\r\t$error" }48 interruptCallback.invoke(request)49 }50 }51 .map { Result.Success(it) }52 .recover { Result.Failure(it as FuelError) }53 .getOrThrow()54 }55 @Throws(FuelError::class)56 suspend fun await(): Response {57 return awaitResult().get()58 }59 companion object {...
FuelClient.kt
Source:FuelClient.kt
...46 success = { json ->47 Log.d("TAG", "dispatch success: $json")48 CommonResult.Success(json)49 },50 failure = { error ->51 Log.e("TAG", "dispatch failure: ${error.localizedMessage.orEmpty()}")52 val message = if (error.localizedMessage.orEmpty().contains("Unable to resolve host")) {53 "Can't connect to server, please check your internet connection"54 } else {55 error.localizedMessage.orEmpty()56 }57 CommonResult.Failure(HttpError(message))58 }59 )60 } catch (e: Exception){61 e.printStackTrace()62 CommonResult.Failure(HttpError("Exception on dispatch"))63 }64 }65 override fun dispatchStream(timeout: Int, timeoutRead: Int): CommonResult<InputStream> {...
Library.kt
Source:Library.kt
...6import androidx.core.app.ActivityCompat7import com.example.eqmobilework.data.LocationEvent8import com.github.kittinunf.fuel.Fuel9import com.github.kittinunf.fuel.core.Request10import com.github.kittinunf.result.failure11import com.github.kittinunf.result.success12import com.google.android.gms.location.LocationServices13import com.google.gson.Gson14import java.util.*15const val TAG = "EQLIB"16class Library {17 // Queue to store log requests and reprocess if any fails18 // This logic can be moved to a permanent storage like SQLite for the final version19 val requests: Queue<LocationEvent> = LinkedList()20 private val baseUrl = "https://httpbin.org/post"21 fun setup(): Boolean {22 return true23 }24 fun log(event: LocationEvent, process: Boolean = true) {25 requests.add(event)26 if (process)27 process()28 }29 fun log(context: Context) {30 val fusedLocationClient =31 LocationServices.getFusedLocationProviderClient(context)32 if (ActivityCompat.checkSelfPermission(33 context,34 Manifest.permission.ACCESS_FINE_LOCATION35 ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(36 context,37 Manifest.permission.ACCESS_COARSE_LOCATION38 ) != PackageManager.PERMISSION_GRANTED39 ) {40 Log.e(TAG, "Location permission not granted")41 return42 }43 fusedLocationClient.lastLocation.addOnSuccessListener {44 val event = if (it == null) {45 // user doesn't have a last know location yet46 // fallback to (0,0)47 LocationEvent(0F, 0F, ext = "empty")48 } else {49 LocationEvent(50 lat = it.latitude.toFloat(),51 lon = it.longitude.toFloat(),52 ext = "empty"53 )54 }55 Log.i(TAG, "Started posting")56 log(event)57 }58 }59 fun process(callback: (() -> Unit)? = null) {60 // return, no requests available to process61 if (requests.isEmpty()) return62 val location = requests.peek()!!63 post(location).responseString { _, _, result ->64 result.success {65 Log.i(TAG, "Posted successfully")66 Log.i(TAG, it)67 // remove from queue if posting was successful68 requests.remove()69 // continue processing the rest of the queue70 process()71 }72 result.failure {73 Log.e(TAG, "Failed to post")74 Log.e(TAG, it.response.statusCode.toString())75 }76 if (callback != null) callback()77 }78 }79 private fun post(location: LocationEvent): Request {80 return Fuel.post(baseUrl).body(Gson().toJson(location))81 }82}...
RequestTask.kt
Source:RequestTask.kt
...45 }46 .getOrThrow()47 }48 .onFailure { error ->49 Fuel.trace { "[RequestTask] on failure (interrupted=${(error as? FuelError)?.causedByInterruption ?: error})" }50 if (error is FuelError && error.causedByInterruption) {51 Fuel.trace { "[RequestTask] execution error\n\r\t$error" }52 interruptCallback.invoke(request)53 }54 }55 .getOrThrow()56 }57}58internal fun Request.toTask(): Callable<Response> = RequestTask(this)...
RequestTaskCallbacks.kt
Source:RequestTaskCallbacks.kt
...11 *12 * @param request [Request] the request that generated the task13 * @param task [Callable<Response>] the task to execute (and perform callbacks on)14 * @param onSuccess [RequestSuccessCallback] the success callback, called when everything went fine15 * @param onFailure [RequestFailureCallback] the failure callback, called when an error occurred16 */17internal class RequestTaskCallbacks(18 private val request: Request,19 private val task: Callable<Response> = request.toTask(),20 private val onSuccess: RequestSuccessCallback,21 private val onFailure: RequestFailureCallback22) : Callable<Response> {23 override fun call(): Response {24 Fuel.trace { "[RequestTaskCallbacks] start request task\n\r\t$request" }25 return runCatching { task.call() }26 .mapCatching { it -> it.also { onSuccess(it) } }27 .getOrElse { error -> FuelError.wrap(error).also { onFailure(it, it.response) }.response }28 }29}...
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!!