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

Best Fuel code snippet using com.github.kittinunf.fuel.core.Handlers.success

Libraries.awesome.kts

Source:Libraries.awesome.kts Github

copy

Full Screen

...528 setTags("fp", "functional")529 }530 link {531 github = "kittinunf/Result"532 desc = "The modelling for success/failure of operations in Kotlin."533 setTags("fp", "functional", "monad")534 }535 link {536 github = "brianegan/bansa"537 desc = "A state container for Kotlin & Java, inspired by Elm & Redux."538 setTags("fp", "functional", "UI", "Interface", "Redux")539 }540 link {541 github = "pardom/redux-kotlin"542 desc = "Direct port of Redux for Kotlin."543 setTags("fp", "functional", "UI", "Interface", "Redux")544 }545 link {546 github = "beyondeye/Reduks"547 desc = "A \"batteries included\" port of Reduxjs for Kotlin+Android"548 setTags("fp", "functional", "UI", "Interface", "Redux")549 }550 link {551 github = "michaelbull/kotlin-result"552 desc = "A Result monad for modelling success or failure operations - inspired by Elm, Rust, & Haskell."553 setTags("fp", "functional", "result", "monad", "either", "type")554 }555 link {556 github = "fork-handles/forkhandles"557 name = "fork-handles/result4k"558 desc = "Result monad for type safe error handling in Kotlin"559 href = "https://github.com/fork-handles/forkhandles/blob/trunk/result4k"560 setTags("fp", "functional", "result", "monad", "either", "type", "error handling")561 }562 link {563 github = "pakoito/Komprehensions"564 desc = "Do comprehensions for Kotlin and 3rd party libraries."565 setTags("comprehensions", "fp", "functional")566 }...

Full Screen

Full Screen

E2EServiceFeatureTest.kt

Source:E2EServiceFeatureTest.kt Github

copy

Full Screen

1package com.example.kata.bank.service.delivery2import arrow.core.Option3import arrow.core.andThen4import arrow.core.getOrElse5import com.example.kata.bank.service.ApplicationBooter6import com.example.kata.bank.service.HTTP7import com.example.kata.bank.service.UnreachableCode8import com.example.kata.bank.service.delivery.`in`.StatementRequestDTO9import com.example.kata.bank.service.delivery.application.ApplicationEngine10import com.example.kata.bank.service.delivery.handlers.AccountsHandler11import com.example.kata.bank.service.delivery.handlers.OperationsHandler12import com.example.kata.bank.service.delivery.handlers.UsersHandler13import com.example.kata.bank.service.delivery.json.MyResponse14import com.example.kata.bank.service.delivery.json.hateoas.Link15import com.example.kata.bank.service.delivery.out.ErrorsDTO16import com.example.kata.bank.service.delivery.out.StatementOutDTO17import com.example.kata.bank.service.domain.AccountRequest18import com.example.kata.bank.service.domain.Id19import com.example.kata.bank.service.domain.Persisted20import com.example.kata.bank.service.domain.accounts.Account21import com.example.kata.bank.service.domain.accounts.Clock22import com.example.kata.bank.service.domain.transactions.Amount23import com.example.kata.bank.service.domain.transactions.Transaction24import com.example.kata.bank.service.domain.transactions.Tx25import com.example.kata.bank.service.infrastructure.accounts.AccountRestrictedRepository26import com.example.kata.bank.service.infrastructure.accounts.AccountsService27import com.example.kata.bank.service.infrastructure.accounts.out.AccountDTO28import com.example.kata.bank.service.infrastructure.operations.AmountDTO29import com.example.kata.bank.service.infrastructure.operations.OperationsRepository30import com.example.kata.bank.service.infrastructure.operations.out.StatementLineDTO31import com.example.kata.bank.service.infrastructure.operations.out.TimeDTO32import com.example.kata.bank.service.infrastructure.operations.out.TransactionDTO33import com.example.kata.bank.service.infrastructure.users.UsersSimpleRepository34import com.example.kata.bank.service.usecases.accounts.DepositUseCase35import com.example.kata.bank.service.usecases.accounts.OpenAccountUseCase36import com.example.kata.bank.service.usecases.accounts.TransferUseCase37import com.example.kata.bank.service.usecases.statements.StatementCreationUseCase38import com.fasterxml.jackson.module.kotlin.readValue39import com.github.kittinunf.fuel.core.FuelError40import com.github.kittinunf.fuel.core.FuelManager41import com.github.kittinunf.fuel.core.Request42import com.github.kittinunf.result.Result43import org.assertj.core.api.AbstractAssert44import org.assertj.core.api.Assertions.assertThat45import org.assertj.core.api.Assertions.fail46import org.assertj.core.api.SoftAssertions47import org.junit.jupiter.api.AfterAll48import org.junit.jupiter.api.BeforeAll49import org.junit.jupiter.api.Test50import org.junit.platform.runner.JUnitPlatform51import org.junit.runner.RunWith52import java.time.LocalDateTime53import java.util.*54@RunWith(JUnitPlatform::class)55class E2EServiceFeatureTest {56 val http = HTTP57 companion object {58 private var application: ApplicationEngine? = null59 @AfterAll60 @JvmStatic61 fun stop() {62 application?.stop()63 }64 @BeforeAll65 @JvmStatic66 fun setup() {67 val (application, serverPort) = ApplicationBooter(configuredApplication).atRandomPort()68 this.application = application69 configurePort(serverPort)70 }71 fun configurePort(serverPort: Int) {72 FuelManager.instance.basePath = "http://localhost:" + serverPort73 }74 val operationsRepository = OperationsRepository()75 val accountRepository = AccountRestrictedRepository.aNew()76 private val configuredApplication: () -> BankWebApplication = {77 BankWebApplication(78 OperationsHandler(79 accountRepository,80 TransferUseCase(accountRepository),81 DepositUseCase(accountRepository),82 operationsRepository),83 AccountsHandler(accountRepository, StatementCreationUseCase(operationsRepository), OpenAccountUseCase(accountRepository)),84 UsersHandler(UsersSimpleRepository()))85 }86 }87 @Test88 fun `create multiple accounts`() {89 val existingAccountSize = readExistingAccounts().size90 openAccount("maria").let(http::request)91 openAccount("maria").let(http::request)92 openAccount("maria").let(http::request)93 assertThat(readExistingAccounts().size).isEqualTo(existingAccountSize + 3)94 }95 private fun readExistingAccounts(): List<MyResponse<AccountDTO>> {96 return (HTTP::get)("/accounts")97 .let(http::request)98 .also { (response, _) ->99 assertThat(response.statusCode).isEqualTo(200)100 }.let { (_, result) -> http.mapper.readValue(result.value) }101 }102 @Test103 fun `an account has a link to self`() {104 val accountId = createAccountLowLevel("maria")105 fetchAccount(accountId)106 .let { it ->107 assertThat(it.self()!!.resource("accounts").isDefined()).isTrue()108 }109 }110 @Test111 fun `detail for an account`() {112 val accountId = Id.random()113 accountRepository.save(Persisted.`for`(aNewAccount("pepe", Account.Number.of("00-00-00-01")), accountId))114 (HTTP::get)(account(accountId))115 .let(http::request)116 .let { (response, result) ->117 assertThat(response.statusCode).isEqualTo(200)118 println(result.value)119 val account = http.mapper.readValue<MyResponse<AccountDTO>>(result.value)120 assertThat(account.response.name).isEqualTo("pepe")121 }122 }123 @Test124 fun `create account`() {125 val accountName = "savings aNewAccount for maria"126 val accountId = createAccountLowLevel(accountName)127 fetchAccount(accountId)128 .let {129 assertThat(it.response.name).isEqualTo(accountName)130 }131 }132 private fun createAccountLowLevel(accountName: String): Id {133 val accountId = openAccount(accountName)134 .let(http::request)135 .let { (_, response) -> http.mapper.readValue<MyResponse<AccountDTO>>(response.value) }136 .selfHref().split("/").last()137 .let { Id.of(it) }138 return accountId139 }140 private fun fetchAccount(accountId: Id): MyResponse<AccountDTO> {141 return HTTP.get("/accounts/${accountId.value}")142 .let(http::request)143 .let { (_, response) -> http.mapper.readValue<MyResponse<AccountDTO>>(response.value) }144 }145 fun <T> MyResponse<T>.selfHref(): String {146 return this.self()!!.href147 }148 fun <T> MyResponse<T>.self(): Link? {149 return links.first { it.rel == "self" }150 }151 private fun openAccount(name: String): Request {152 return (HTTP::post)("accounts", """{"name": "$name"}""")153 }154 @Test155 fun `deposit - a correct request`() {156 val accountId = Id.random()157 accountRepository.save(Persisted.`for`(aNewAccount(), accountId))158 val existingOperations = `operationsFor!`(accountId)159 depositRequest(accountId, """160{161 "type": "deposit",162 "amount": {163 "value": "1234.56",164 "currency": "EUR"165},166 "description": "rent for this month"167}168 """).let(http::request)169 .let { (response, result) ->170 assertThat(response.statusCode).isEqualTo(200)171 val response = http.mapper.readValue<MyResponse<Unit>>(result.value)172 println(response)173 assertThat(response.links).hasSize(1)174 assertThat(response.links).filteredOn { it.rel == "list" }.isNotEmpty()175 }176 val newOperations = `operationsFor!`(accountId)177 this.bIsSupersetOfA(a = existingOperations, b = newOperations)178 assertThat(newOperations.size).isGreaterThan(existingOperations.size)179 TransactionAssert.assertThat(newOperations.last().value).isEqualToIgnoringDate(Transaction.Deposit(Tx(Amount.of("1234.56"), anyDate(), "rent for this month")))180 }181 @Test182 fun `wire transfer - a correct request`() {183 val accountId = Id.random()184 accountRepository.save(Persisted.`for`(aNewAccount(), accountId))185 val existingOperations = `operationsFor!`(accountId)186 val destinationId = Id.random()187 accountRepository.save(Persisted.`for`(aNewAccount(accountNumber = Account.Number.of("11")), destinationId))188 depositRequest(accountId, """189{190 "type": "transfer",191 "amount": {192 "value": "1234.56",193 "currency": "EUR"194 },195 "destination":{196 "number":"11",197 "owner": "Maria"198 },199 "description": "rent for this month"200}201""".trimIndent()).let(http::request)202 .let { (response, result) ->203 assertThat(response.statusCode).isEqualTo(200)204 val response = http.mapper.readValue<MyResponse<Unit>>(result.value)205 println(response)206 assertThat(response.links).hasSize(1)207 assertThat(response.links).filteredOn { it.rel == "list" }.isNotEmpty()208 }209 val newOperations = `operationsFor!`(accountId)210 this.bIsSupersetOfA(a = existingOperations, b = newOperations)211 assertThat(newOperations.size).isGreaterThan(existingOperations.size)212// TransactionAssert.assertThat(newOperations.last().value).isEqualToIgnoringDate(Transaction.Transfer.Emitted(Tx(Amount.of("1234.56"), anyDate(), "rent for this month"),213// Transaction.Transfer.Completed(accountId, destinationId)))214// TransactionAssert.assertThat(`operationsFor!`(destinationId).last().value).isEqualToIgnoringDate(Transaction.Transfer.Received(Tx(Amount.of("1234.56"), anyDate(),215// "rent for this month"),216// Transaction.Transfer.Completed(accountId, destinationId)))217 }218 private fun <T> forceGet(a: Option<T>): T {219 return a.getOrElse {220 fail("this element must be present")221 throw UnreachableCode()222 }223 }224 private fun operationsFor(accountId: Id): Option<List<Persisted<Transaction>>> {225 return AccountsService(accountRepository).operationsFor(accountId)226 }227 private val `operationsFor!` = this::operationsFor andThen this::forceGet228 private fun anyDate(): LocalDateTime {229 return LocalDateTime.now()230 }231 fun bIsSupersetOfA(a: List<Persisted<Transaction>>, b: List<Persisted<Transaction>>) {232 a.forEach {233 b.contains(it)234 }235 }236 class TransactionAssert(val actualT: Transaction) : AbstractAssert<TransactionAssert, Transaction>(actualT, TransactionAssert::class.java) {237 fun isEqualToIgnoringDate(transaction: Transaction): TransactionAssert {238 assertThat(transaction).isNotNull239 val softly = SoftAssertions()240 softly.assertThat(this.actualT.tx.amount).isEqualTo(transaction.tx.amount)241 softly.assertThat(this.actualT.tx.description).isEqualTo(transaction.tx.description)242 softly.assertAll()243 return this244 }245 companion object {246 // 3 - A fluent entry point to your specific assertion class, use it with static import.247 fun assertThat(actual: Transaction): TransactionAssert {248 return TransactionAssert(actual)249 }250 }251 }252 @Test253 fun `list the operations`() {254 val accountId = Id.random()255 accountRepository.save(Persisted.`for`(aNewAccount(), accountId))256 accountRepository.findBy(accountId)257 .map {258 it.value.deposit(Amount.Companion.of("100"), "rent, part 1")259 it.value.deposit(Amount.Companion.of("200"), "rent, part 2")260 }261 (HTTP::get)(operations(accountId))262 .let(http::request)263 .let { (response, result) ->264 assertThat(response.statusCode).isEqualTo(200)265 println(result.value)266 val response = http.mapper.readValue<List<MyResponse<TransactionDTO>>>(result.value)267 assertThat(response).hasSize(2)268 }269 }270 @Test271 fun `create a statement, without any filter - creates a new Cost`() {272 val accountId = Id.random()273 accountRepository.save(Persisted.`for`(aNewAccount(), accountId))274 accountRepository.findBy(accountId)275 .map {276 it.value.deposit(Amount.Companion.of("100"), "rent, part 1")277 it.value.deposit(Amount.Companion.of("200"), "rent, part 2")278 }279 val previousCosts = forceGet(transactionsFor(accountId)).filter { it is Transaction.Cost }.size280 createStatement(accountId.value, StatementRequestDTO("statement"))281 .let(http::request)282 .let { (response, result) ->283 assertThat(response.statusCode).isEqualTo(200)284 println(result.value)285 val response = http.mapper.readValue<MyResponse<String>>(result.value)286 val statementPair = response.links.find { it.rel == "self" }?.resource("statements")!!287 statementPair.map {288 val (_, statementId) = it289 assertThat(operationsRepository.findBy(Id.of(statementId)).isDefined()).isTrue()290 val newCosts = forceGet(transactionsFor(accountId)).filter { it is Transaction.Cost }.size291 assertThat(newCosts).isEqualTo(previousCosts + 1)292 }293 }294 }295 @Test296 fun `fetch a statement`() {297 val accountId = Id.random()298 accountRepository.save(Persisted.`for`(aNewAccount(), accountId))299 val statementId = accountRepository.findBy(accountId)300 .map {301 it.value.deposit(Amount.Companion.of("100"), "rent, part 1")302 it.value.deposit(Amount.Companion.of("200"), "rent, part 2")303 StatementCreationUseCase(operationsRepository).createStatement(it.value, AccountRequest.StatementRequest.all())304 }.getOrElse { throw UnreachableCode() }305 (HTTP::get)(statement(accountId, statementId))306 .let(http::request)307 .let { (response, result) ->308 assertThat(response.statusCode).isEqualTo(200)309 result310 }.let(readAsMyResponseStatementOutDTO)311 .let { x ->312 val deposits = setTime(x, fixedTimeDTO)313 assertThat(deposits).contains(314 StatementLineDTO(AmountDTO.EUR("100.00"), "rent, part 1", fixedTimeDTO, "deposit", AmountDTO.EUR("100.00")),315 StatementLineDTO(AmountDTO.EUR("200.00"), "rent, part 2", fixedTimeDTO, "deposit", AmountDTO.EUR("300.00")))316 }317 }318 val readAsMyResponseStatementOutDTO: (Result.Success<String, FuelError>) -> MyResponse<StatementOutDTO> = { http.mapper.readValue(it.value) }319 private fun statement(accountId: Id, statementId: Id) =320 "/accounts/${accountId.value}/statements/${statementId.value}"321 private fun setTime(coll: MyResponse<StatementOutDTO>, value: TimeDTO): List<StatementLineDTO> {322 return coll.response.statementLines.map {323 it.copy(time = value)324 }325 }326 @Test327 fun `try to create an unsupported type of request`() {328 val accountId = Id.random()329 accountRepository.save(Persisted.`for`(aNewAccount(), accountId))330 createStatement(accountId.value, StatementRequestDTO("unsupported"))331 .let { http.assertFailedRequest(it, http::assertError) }332 .let { (response, _) ->333 assertThat(response.statusCode).isEqualTo(400)334 val errors = http.mapper.readValue<MyResponse<ErrorsDTO>>(String(response.data).replace("\\n".toRegex(), ""))335 assertThat(errors.response.messages).contains("This operation is not supported for now")336 }337 }338 private fun operations(accountId: Id) = "/accounts/${accountId.value}/operations"339 private fun aNewAccount(accountNumber: Account.Number = Account.Number.of(Id.random().value)) = aNewAccount("savings account #" + Random().nextInt(10), accountNumber)340 private fun account(accountId: Id) = "/accounts/${accountId.value}"341 private fun aNewAccount(accountName: String, accountNumber: Account.Number) = Account(Clock.aNew(), accountName, number = accountNumber)342 private fun depositRequest(accountId: Id, jsonPayload: String): Request {343 return http.post("accounts/${accountId.value}/operations", jsonPayload)344 }345 private fun createStatement(value: String, request: StatementRequestDTO): Request {346 return http.post("/accounts/$value", request)347 }348 private fun transactionsFor(accountId: Id) = accountRepository.findBy(accountId).map { it.value.findAll().map { it.value } }349 val fixedTimeDTO = TimeDTO("2018-10-12 23:59:00", "2018-10-12T23:59:00")350}...

Full Screen

Full Screen

Users.kt

Source:Users.kt Github

copy

Full Screen

...233 }234}235data class SsoCode(236 val realm: String,237 val successUrl: String,238 val tokenId: String239)...

Full Screen

Full Screen

UserFlowTest.kt

Source:UserFlowTest.kt Github

copy

Full Screen

1package com.example.kata.bank.service.delivery.e2e2import com.example.kata.bank.service.ApplicationBooter3import com.example.kata.bank.service.HTTP4import com.example.kata.bank.service.delivery.AccountsHandlerClient5import com.example.kata.bank.service.delivery.BankWebApplication6import com.example.kata.bank.service.delivery.`in`.StatementRequestDTO7import com.example.kata.bank.service.delivery.application.ApplicationEngine8import com.example.kata.bank.service.delivery.handlers.AccountsHandler9import com.example.kata.bank.service.delivery.handlers.OperationsHandler10import com.example.kata.bank.service.delivery.handlers.UsersHandler11import com.example.kata.bank.service.delivery.json.MyResponse12import com.example.kata.bank.service.delivery.out.StatementOutDTO13import com.example.kata.bank.service.domain.Id14import com.example.kata.bank.service.domain.Persisted15import com.example.kata.bank.service.domain.transactions.Transaction16import com.example.kata.bank.service.infrastructure.accounts.AccountRestrictedRepository17import com.example.kata.bank.service.infrastructure.accounts.out.AccountDTO18import com.example.kata.bank.service.infrastructure.operations.AmountDTO19import com.example.kata.bank.service.infrastructure.operations.OperationsRepository20import com.example.kata.bank.service.infrastructure.users.UsersSimpleRepository21import com.example.kata.bank.service.usecases.accounts.DepositUseCase22import com.example.kata.bank.service.usecases.accounts.OpenAccountUseCase23import com.example.kata.bank.service.usecases.accounts.TransferUseCase24import com.example.kata.bank.service.usecases.statements.StatementCreationUseCase25import com.fasterxml.jackson.module.kotlin.readValue26import com.github.kittinunf.fuel.core.FuelError27import com.github.kittinunf.fuel.core.FuelManager28import com.github.kittinunf.fuel.core.Request29import com.github.kittinunf.fuel.core.Response30import com.github.kittinunf.result.Result31import org.assertj.core.api.Assertions.assertThat32import org.junit.jupiter.api.AfterAll33import org.junit.jupiter.api.BeforeAll34import org.junit.jupiter.api.Test35import org.junit.platform.runner.JUnitPlatform36import org.junit.runner.RunWith37@RunWith(JUnitPlatform::class)38class UserFlowTest {39 val http = HTTP40 companion object {41 private var application: ApplicationEngine? = null42 @AfterAll43 @JvmStatic44 fun stop() {45 application?.stop()46 }47 @BeforeAll48 @JvmStatic49 fun setup() {50 val (application, serverPort) = ApplicationBooter(configuredApplication).atRandomPort()51 this.application = application52 configurePort(serverPort)53 }54 fun configurePort(serverPort: Int) {55 FuelManager.instance.basePath = "http://localhost:" + serverPort56 }57 val operationsRepository = OperationsRepository()58 val accountRepository = AccountRestrictedRepository.aNew()59 private val configuredApplication: () -> BankWebApplication = {60 BankWebApplication(61 OperationsHandler(62 accountRepository,63 TransferUseCase(accountRepository),64 DepositUseCase(accountRepository),65 operationsRepository),66 AccountsHandler(accountRepository, StatementCreationUseCase(operationsRepository), OpenAccountUseCase(accountRepository)),67 UsersHandler(UsersSimpleRepository()))68 }69 }70 @Test71 fun `get the balance after a few deposits`() {72 val accountId = createAccount()73 deposit10(accountId)74 deposit10(accountId)75 deposit10(accountId)76 deposit10(accountId)77 val statementUri = `create statement and get its uri`(accountId)78 val response = `fetch statement`(statementUri)79 assertThat(response.response.statementLines.first().balance).isEqualTo(AmountDTO.EUR("" + (4 * 10 - 1) + ".00"))80 }81 private fun `fetch statement`(statementUri: String) =82 http.get(statementUri).let(http::request).let(readAsStatementDto)83 private fun `create statement and get its uri`(accountId: Id) =84 createStatement(accountId, StatementRequestDTO("statement")).let(http::request).let(readAsAny).links.first { it.rel == "self" }.href85 private fun createAccount(): Id {86 val jsonPayload = AccountsHandlerClient.createAccount("john doe")87 return Id.of((HTTP::post)("/accounts", jsonPayload).let(http::request).let(readAsAccountDto).let { it -> it.links.first { it.rel == "self" }.href.split("/").last() })88 }89 val readAsAccountDto: (Pair<Response, Result.Success<String, FuelError>>) -> MyResponse<AccountDTO> = { (_, result) -> http.mapper.readValue(result.value) }90 val readAsStatementDto: (Pair<Response, Result.Success<String, FuelError>>) -> MyResponse<StatementOutDTO> = { (_, result) -> http.mapper.readValue(result.value) }91 val readAsAny: (Pair<Response, Result.Success<String, FuelError>>) -> MyResponse<Any> = { (_, result) -> http.mapper.readValue(result.value) }92 fun bIsSupersetOfA(a: List<Persisted<Transaction>>, b: List<Persisted<Transaction>>) {93 a.forEach {94 b.contains(it)95 }96 }97 private fun deposit10(accountId: Id) {98 depositRequest(accountId, AccountsHandlerClient.deposit("10")).let(http::request)99 }100 private fun depositRequest(accountId: Id, jsonPayload: String): Request {101 return http.post("accounts/${accountId.value}/operations", jsonPayload)102 }103 private fun createStatement(value: Id, request: StatementRequestDTO): Request {104 return http.post("/accounts/${value.value}", request)105 }106}...

Full Screen

Full Screen

UpdateChecker.kt

Source:UpdateChecker.kt Github

copy

Full Screen

...32 return33 }34 //TODO: add job name to constants at build time35 val build = job.lastSuccessfulBuild ?: run {36 logger.error("no successful build found")37 return38 }39 with(build) {40 when {41 number > instance.buildNumber -> {42 logger.warn("Mod out of date! New build $number available at $url")43 val difference = number - instance.buildNumber44 LocationHandler.sendToLocations(45 msg = "MatterLink out of date! You are $difference builds behind! Please download new version from $url",46 x = 0, y = 0, z = 0, dimension = null,47 event = ChatEvent.STATUS,48 cause = "MatterLink update notice"49 )50 }...

Full Screen

Full Screen

CancellableRequest.kt

Source:CancellableRequest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core.requests2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import java.util.concurrent.Future7/**8 * Request extension that adds [cancel] to a Running or Pending [Request].9 *10 * @see [com.github.kittinunf.fuel.core.Deserializable] used when using handlers11 *12 * @param wrapped [Request] the request that will be running13 * @param future [Future<Response>] the running or pending request execution that will yield a [Response]14 */15class CancellableRequest private constructor(private val wrapped: Request, private val future: Future<Response>) :16 Request by wrapped, Future<Response> by future {17 private val interruptCallback by lazy { executor.interruptCallback }18 private val executor by lazy { request.executionOptions }19 override val request: CancellableRequest = this20 override fun toString() = "Cancellable[\n\r\t$wrapped\n\r] done=$isDone cancelled=$isCancelled"21 /**22 * Cancel the request, interrupt if in progress23 */24 fun cancel() = future.cancel(true)25 /**26 * Wait for the request to be finished, error-ed, cancelled or interrupted27 * @return [Response]28 */29 fun join(): Response = runCatching { future.get() }.fold(30 onSuccess = { it -> it.also { Fuel.trace { "[CancellableRequest] joined to $it" } } },31 onFailure = { error ->32 Response.error(url).also {33 Fuel.trace { "[CancellableRequest] joined to $error" }34 if (FuelError.wrap(error).causedByInterruption) {35 interruptCallback.invoke(wrapped)36 }37 }38 }39 )40 companion object {41 val FEATURE: String = CancellableRequest::class.java.canonicalName42 fun enableFor(request: Request, future: Future<Response>): CancellableRequest {43 // Makes sure the "newest" request is stored, although it should always be the same.44 val current = getFor(request) ?: CancellableRequest(request, future)45 if (request !== current) {46 request.enabledFeatures[FEATURE] = current47 }48 return current49 }50 fun getFor(request: Request): CancellableRequest? {51 return request.enabledFeatures[FEATURE] as? CancellableRequest52 }53 }54}55/**56 * Tries to cancel the request.57 *58 * @note Not all [Request] can be cancelled, so this may fail without reason.59 * @param mayInterruptIfRunning [Boolean] if the thread executing this task should be interrupted; otherwise,60 * in-progress tasks are allowed to complete.61 * @return [Boolean] true if it was cancelled, false otherwise62 */63fun Request.tryCancel(mayInterruptIfRunning: Boolean = true): Boolean {64 val feature = request.enabledFeatures[CancellableRequest.FEATURE] as? CancellableRequest65 return feature?.cancel(mayInterruptIfRunning) ?: false66}67/**68 * Get the current cancellation state69 *70 * @note This can be used in code which may not be interrupted but has certain break points where it can be interrupted.71 * @return [Boolean] true if cancelled, false otherwise72 */73val Request.isCancelled: Boolean get() = CancellableRequest.getFor(request)?.isCancelled ?: false...

Full Screen

Full Screen

FuelHttpClient.kt

Source:FuelHttpClient.kt Github

copy

Full Screen

1package com.github.christophpickl.kpotpourri.http4k_fuel2import com.github.christophpickl.kpotpourri.http4k.DefiniteRequestBody3import com.github.christophpickl.kpotpourri.http4k.Http4kException4import com.github.christophpickl.kpotpourri.http4k.HttpMethod4k5import com.github.christophpickl.kpotpourri.http4k.Request4k6import com.github.christophpickl.kpotpourri.http4k.Response4k7import com.github.christophpickl.kpotpourri.http4k.internal.HttpClient8import com.github.christophpickl.kpotpourri.http4k.internal.HttpClientFactory9import com.github.christophpickl.kpotpourri.http4k.internal.MetaMap10import com.github.kittinunf.fuel.core.FuelManager11import com.github.kittinunf.fuel.httpDelete12import com.github.kittinunf.fuel.httpGet13import com.github.kittinunf.fuel.httpPost14import com.github.kittinunf.fuel.httpPut15import com.github.kittinunf.result.Result16import mu.KotlinLogging.logger17class FuelHttpClientFactory : HttpClientFactory {18 override fun build(metaMap: MetaMap) =19 FuelHttpClient(metaMap)20}21class FuelHttpClient(private val metaMap: MetaMap) : HttpClient {22 private val log = logger {}23 init {24 // get rid of: redirectResponseInterceptor(this), validatorResponseInterceptor(200..299)25 FuelManager.instance.removeAllResponseInterceptors()26 }27 private fun String.httpAny(method: HttpMethod4k) =28 when (method) {29 HttpMethod4k.GET -> { httpGet() }30 HttpMethod4k.POST -> { httpPost() }31 HttpMethod4k.PUT -> { httpPut() }32 HttpMethod4k.DELETE -> { httpDelete() }33 HttpMethod4k.PATCH -> { httpPost() } // fuel hack, as it doesnt support patch34 }35 override fun execute(request4k: Request4k): Response4k {36 log.debug { "execute($request4k) ... $metaMap" }37 val (_, response, result) = request4k.url.httpAny(request4k.method)38 .apply {39 header(request4k.headers)40 if (request4k.method == HttpMethod4k.PATCH) {41 // workaround for fuel as it does not support PATCH method42 header("X-HTTP-Method-Override" to "PATCH")43 }44 request4k.requestBody?.let {45 when(it) {46 is DefiniteRequestBody.DefiniteStringBody ->47 body(it.string)48 is DefiniteRequestBody.DefiniteBytesBody->49 body(it.bytes)50 }51 }52 }53 // .timeout(timeout)54 // .readTimeout(readTimeout).55 .responseString()56 // .response(handler: (Request, Response, Result<ByteArray, FuelError>) -> Unit)57 val firstHeaderValuesOnly = response.httpResponseHeaders.map { it.key to it.value.first() }.toMap()58 return when (result) {59 is Result.Success -> Response4k(60 statusCode = response.httpStatusCode,61 bodyAsString = result.value,62 headers = firstHeaderValuesOnly63 )64 is Result.Failure -> throw Http4kException("Failure result from fuel: $result") // if internal fuel error handlers got triggered65 }66 }67}...

Full Screen

Full Screen

ResponseHandlers.kt

Source:ResponseHandlers.kt Github

copy

Full Screen

1import com.github.kittinunf.fuel.core.FuelError2import com.github.kittinunf.fuel.core.Request3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.result.Result5object ResponseHandlers {6 val emptyHandler : (Request, Response, Result<String, FuelError>) -> Unit = {7 _, _, result-> when(result) {8 is Result.Failure -> {9 println("FAILURE:...")10 result.error.exception.printStackTrace()11 }12 is Result.Success -> {13 println("SUCCESS:${result.get()}")14 }15 else -> { }16 }17 }18}...

Full Screen

Full Screen

success

Using AI Code Generation

copy

Full Screen

1when (result) {2is Result.Failure -> {3val ex = result.getException()4println(ex)5}6is Result.Success -> {7val data = result.get()8println(data)9}10}11}12result.success { data ->13println(data)14}15}16val (request, response, result) = Fuel.get("/v1/vehicles").responseString()17println("result: $result")18println("response: $response")19{20}21println("result: $result")22println("response: $response")23println("result: $result")24println("response: $response")25result: Result.Failure(java.net.UnknownHostException: localhost)

Full Screen

Full Screen

success

Using AI Code Generation

copy

Full Screen

1when (result) {2is Result.Success -> {3println(result.get())4}5is Result.Failure -> {6println(result.error)7}8}9when (result) {10is Result.Success -> {11println(result.get())12}13is Result.Failure -> {14println(result.error)15}16}17when (result) {18is Result.Success -> {19println(result.get())20}21is Result.Failure -> {22println(result.error)23}24}25when (result) {26is Result.Success -> {27println(result.get())28}29is Result.Failure -> {30println(result.error)31}32}33when (result) {34is Result.Success -> {35println(result.get())36}37is Result.Failure -> {38println(result.error)39}40}41when (result) {42is Result.Success -> {43println(result.get())44}45is Result.Failure -> {46println(result.error)47}48}49when (result) {50is Result.Success -> {51println(result.get())52}53is Result.Failure -> {54println(result.error)55}56}57val (request, response, result) = Fuel

Full Screen

Full Screen

success

Using AI Code Generation

copy

Full Screen

1 }2 }3 }4 }5 }6 }7 }8 }9 }10 }

Full Screen

Full Screen

success

Using AI Code Generation

copy

Full Screen

1fun main(args: Array<String>) {2result.success { data -> println(data) }3}4fun main(args: Array<String>) {5result.failure { error -> println(error) }6}7fun main(args: Array<String>) {8println(request)9}10fun main(args: Array<String>) {11println(response)12}13fun main(args: Array<String>) {14println(result)15}16fun main(args: Array<String>) {17val (data, error) = result18println(data)19println(error)20}21fun main(args: Array<String>) {22val (data, error) = result23println(data)24println(error)25}26fun main(args: Array<String>) {27val (headers, statusCode, data) = response28println(headers)29println(statusCode)30println(data)31}32fun main(args: Array<String>) {33val (

Full Screen

Full Screen

success

Using AI Code Generation

copy

Full Screen

1val (data, error) = result2if (data != null) {3println(data)4}5}6val (data, error) = result7if (data != null) {8println(data.toString())9}10}11val (data, error) = result12if (data != null) {13println(data.toString())14}15}16val (data, error) = result17if (data != null) {18println(data.toString())19} else {20println(error.toString())21}22}23val (data, error) = result24if (data != null) {25println(data.toString())26} else {27println(error.toString())28}29}30val (data, error) = result31if (data != null) {32println(data.toString())33} else {34println(error.toString())35}36}

Full Screen

Full Screen

success

Using AI Code Generation

copy

Full Screen

1 val (request, response, result) = result2 val (request, response, result) = result3 val (request, response, result) = result4 val (request, response, result) = result5 val (request, response, result) = result6 val (request, response, result) = result7 val (request, response, result) = result8 val (request, response, result) = result9 val (_, _, result) = Fuel.get

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.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in Handlers

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful