How to use interrupt method of com.github.kittinunf.fuel.core.Request class

Best Fuel code snippet using com.github.kittinunf.fuel.core.Request.interrupt

DefaultRequest.kt

Source:DefaultRequest.kt Github

copy

Full Screen

...289 }290 /**291 * Add a [InterruptCallback] to the [RequestExecutionOptions]292 *293 * @see RequestExecutionOptions.interruptCallbacks294 *295 * @return self296 */297 override fun interrupt(interrupt: InterruptCallback) = request.also {298 it.executionOptions.interruptCallbacks.plusAssign(interrupt)299 }300 /**301 * Overwrite the [Request] [timeout] in milliseconds302 *303 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour304 * @note the default client sets [java.net.HttpURLConnection.setConnectTimeout]305 *306 * @param timeout [Int] timeout in milliseconds307 * @return self308 */309 override fun timeout(timeout: Int) = request.also {310 it.executionOptions.timeoutInMillisecond = timeout311 }312 /**...

Full Screen

Full Screen

CancellableRequestTest.kt

Source:CancellableRequestTest.kt Github

copy

Full Screen

...33 val request = Fuel.post(mock.path("cancel-during-request"))34 val running = request35 .requestProgress { _, _ -> request.tryCancel() }36 .body("my-body")37 .interrupt { semaphore.release() }38 .response(expectNoResponseCallbackHandler())39 // Run the request40 if (!semaphore.tryAcquire(5, TimeUnit.SECONDS)) {41 fail("Expected request to be cancelled via interruption")42 }43 assertThat(running.isDone, equalTo(true))44 assertThat(running.isCancelled, equalTo(true))45 }46 @Test47 fun testCancellationDuringReceivingResponse() {48 val manager = FuelManager()49 val interruptedSemaphore = Semaphore(0)50 val responseWrittenSemaphore = Semaphore(0)51 val bytes = ByteArray(10 * manager.progressBufferSize).apply { Random().nextBytes(this) }52 val file = File.createTempFile("random-bytes", ".bin")53 mock.chain(54 request = mock.request().withMethod(Method.GET.value).withPath("/cancel-response"),55 response = mock.response().withBody(bytes).withDelay(TimeUnit.MILLISECONDS, 200)56 )57 val running = manager.download(mock.path("cancel-response"))58 .fileDestination { _, _ -> file }59 .responseProgress { readBytes, _ ->60 responseWrittenSemaphore.release()61 Thread.sleep(200)62 if (readBytes > 9 * manager.progressBufferSize)63 fail("Expected request to be cancelled by now")64 }65 .interrupt { interruptedSemaphore.release() }66 .response(expectNoResponseCallbackHandler())67 if (!responseWrittenSemaphore.tryAcquire(3, 5, TimeUnit.SECONDS)) {68 fail("Expected body to be at least ${3 * manager.progressBufferSize} bytes")69 }70 // Cancel while writing body71 running.cancel()72 // Run the request73 if (!interruptedSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {74 fail("Expected request to be cancelled via interruption")75 }76 assertThat(running.isDone, equalTo(true))77 assertThat(running.isCancelled, equalTo(true))78 assertThat("Expected file to be incomplete", file.length() < bytes.size, equalTo(true))79 }80 // Random Test Failure when interruptSemaphore didn't acquired on 5 secs81 @Test82 fun testCancellationInline() {83 val interruptSemaphore = Semaphore(0)84 val bodyReadSemaphore = Semaphore(0)85 mock.chain(86 request = mock.request().withMethod(Method.POST.value).withPath("/cancel-inline"),87 response = mock.reflect().withDelay(TimeUnit.MILLISECONDS, 200)88 )89 val running = FuelManager()90 .request(Method.POST, mock.path("cancel-inline"), listOf("foo" to "bar"))91 .authentication().basic("username", "password")92 .body(93 { ByteArrayInputStream("my-body".toByteArray()).also { bodyReadSemaphore.release() } },94 { "my-body".length.toLong() }95 )96 .interrupt { interruptSemaphore.release() }97 .response(expectNoResponseCallbackHandler())98 if (!bodyReadSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {99 fail("Expected body to be serialized")100 }101 running.cancel()102 if (!interruptSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {103 fail("Expected request to be cancelled via interruption")104 }105 assertThat(running.isDone, equalTo(true))106 assertThat(running.isCancelled, equalTo(true))107 }108 @Test109 fun interruptCallback() {110 val manager = FuelManager()111 val interruptSemaphore = Semaphore(0)112 val responseWrittenCallback = Semaphore(0)113 val bytes = ByteArray(10 * manager.progressBufferSize).apply { Random().nextBytes(this) }114 mock.chain(115 request = mock.request().withMethod(Method.GET.value).withPath("/bytes"),116 response = mock.response()117 .withBody(BinaryBody(bytes, MediaType.OCTET_STREAM))118 .withDelay(TimeUnit.MILLISECONDS, 200)119 )120 val file = File.createTempFile(bytes.toString(), null)121 val running = FuelManager()122 .download(mock.path("bytes"))123 .fileDestination { _, _ -> file }124 .header(Headers.CONTENT_TYPE, "application/octet-stream")125 .responseProgress { _, _ ->126 responseWrittenCallback.release()127 Thread.sleep(200)128 }129 .interrupt { interruptSemaphore.release() }130 .response(expectNoResponseCallbackHandler())131 if (!responseWrittenCallback.tryAcquire(5, TimeUnit.SECONDS)) {132 fail("Expected response to be partially written")133 }134 running.cancel()135 if (!interruptSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {136 fail("Expected request to be cancelled via interruption")137 }138 assertThat(running.isDone, equalTo(true))139 assertThat(running.isCancelled, equalTo(true))140 }141}...

Full Screen

Full Screen

RestCallBuildProcess.kt

Source:RestCallBuildProcess.kt Github

copy

Full Screen

...32 FuelManager.instance.addResponseInterceptor(redirectResponseInterceptor())33 }34 override fun start() = prepareCall()35 override fun waitFor() = executeCall()36 override fun interrupt() = interruptCall()37 override fun isInterrupted() = isInterrupted38 override fun isFinished() = isInterrupted || normallyFinished39 private fun interruptCall() {40 call.interrupt {41 buildLogger.message("REST call to $endpoint interrupted")42 }43 isInterrupted = true44 }45 private fun prepareCall() {46 val restCallType = context.getRestCallType() ?: throw RunBuildException("Cannot determine REST call type")47 val timeout = context.getRequestTimeout()?.toIntOrNull()?: 1500048 call = when (restCallType) {49 GET -> endpoint.httpGet(context.getRequestParams()).timeout(timeout).timeoutRead(timeout)50 POST -> endpoint.httpPost(context.getRequestParams()).timeout(timeout).timeoutRead(timeout)51 PUT -> endpoint.httpPut(context.getRequestParams()).timeout(timeout).timeoutRead(timeout)52 DELETE -> endpoint.httpDelete(context.getRequestParams()).timeout(timeout).timeoutRead(timeout)53 }54 val user = context.getRequestAuthenticationUser()55 if (user != null) call.authenticate(user.userName, user.password)...

Full Screen

Full Screen

SuspendableRequest.kt

Source:SuspendableRequest.kt Github

copy

Full Screen

...8/**9 * Coroutine version of [RequestTask]. Turns a [Request] into an executable, suspendable, coroutine.10 */11class SuspendableRequest private constructor(private val wrapped: Request) : Request by wrapped {12 private val interruptCallback by lazy { executor.interruptCallback }13 private val executor by lazy { request.executionOptions }14 private val client by lazy { executor.client }15 private fun prepareRequest(request: Request): Request = executor.requestTransformer(request)16 private suspend fun executeRequest(request: Request): Pair<Request, Response> {17 return runCatching { Pair(request, client.awaitRequest(request)) }18 .recover { error -> throw FuelError.wrap(error, Response(url)) }19 .getOrThrow()20 }21 private fun prepareResponse(result: Pair<Request, Response>): Response {22 val (request, response) = result23 return runCatching { executor.responseTransformer(request, response) }24 .mapCatching { transformedResponse ->25 val valid = executor.responseValidator(transformedResponse)26 if (valid) transformedResponse27 else throw FuelError.wrap(HttpException(transformedResponse.statusCode, transformedResponse.responseMessage), transformedResponse)28 }29 .recover { error -> throw FuelError.wrap(error, response) }30 .getOrThrow()31 }32 suspend fun awaitResult(): Result<Response, FuelError> {33 return runCatching { prepareRequest(request) }34 .mapCatching { executeRequest(it) }35 .mapCatching { pair ->36 // Nested runCatching so response can be rebound37 runCatching { prepareResponse(pair) }38 .recover { error ->39 error.also { Fuel.trace { "[RequestTask] execution error\n\r\t$error" } }40 throw FuelError.wrap(error, pair.second)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 {60 private val FEATURE = SuspendableRequest::class.java.canonicalName61 fun enableFor(request: Request): SuspendableRequest {62 // Makes sure the "newest" request is stored, although it should always be the same....

Full Screen

Full Screen

CancellableRequest.kt

Source:CancellableRequest.kt Github

copy

Full Screen

...13 * @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

RequestTask.kt

Source:RequestTask.kt Github

copy

Full Screen

...9/**10 * Synchronous version of [SuspendableRequest]. Turns a [Request] into a [Callable]11 */12internal class RequestTask(internal val request: Request) : Callable<Response> {13 private val interruptCallback by lazy { executor.interruptCallback }14 private val executor by lazy { request.executionOptions }15 private val client by lazy { executor.client }16 private fun prepareRequest(request: Request): Request = executor.requestTransformer(request)17 @Throws(FuelError::class)18 private fun executeRequest(request: Request): RequestTaskResult {19 return runCatching { Pair(request, client.executeRequest(request)) }20 .recover { error -> throw FuelError.wrap(error, Response(request.url)) }21 .getOrThrow()22 }23 @Throws(FuelError::class)24 private fun prepareResponse(result: RequestTaskResult): Response {25 val (request, response) = result26 return runCatching { executor.responseTransformer(request, response) }27 .mapCatching { transformedResponse ->28 val valid = executor.responseValidator(transformedResponse)29 if (valid) transformedResponse30 else throw FuelError.wrap(HttpException(transformedResponse.statusCode, transformedResponse.responseMessage), transformedResponse)31 }32 .recover { error -> throw FuelError.wrap(error, response) }33 .getOrThrow()34 }35 @Throws(FuelError::class)36 override fun call(): Response {37 return runCatching { prepareRequest(request) }38 .mapCatching { executeRequest(it) }39 .mapCatching { pair ->40 // Nested runCatching so response can be rebound41 runCatching { prepareResponse(pair) }42 .recover { error ->43 error.also { Fuel.trace { "[RequestTask] execution error\n\r\t$error" } }44 throw FuelError.wrap(error, pair.second)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)

Full Screen

Full Screen

Network.kt

Source:Network.kt Github

copy

Full Screen

...19 val responseJson = response.body().asString("application/json")20 println(responseJson)21 when (result) {22 is Result.Failure -> {23 println("Trying to interrupt and cancel request")24 exitProcess(1)25 }26 is Result.Success -> {27 println("Success")28 val responseBodyObjectList = parseJsonToResponseBodyObject(responseJson)29 if (responseBodyObjectList != null) {30 writeToFile(responseBodyObjectList, tokenList)31 } else {32 request.tryCancel()33 println("Failed: Nothing in the object")34 }35 }36 }37 }...

Full Screen

Full Screen

TaskRequest.kt

Source:TaskRequest.kt Github

copy

Full Screen

...4import com.github.kittinunf.fuel.core.Response5import java.io.InterruptedIOException6import java.util.concurrent.Callable7open class TaskRequest(val request: Request) : Callable<Response> {8 var interruptCallback: ((Request) -> Unit)? = null9 override fun call(): Response {10 try {11 val modifiedRequest = request.requestInterceptor?.invoke(request) ?: request12 val response = request.client.executeRequest(modifiedRequest)13 val modifiedResponse = request.responseInterceptor?.invoke(modifiedRequest, response) ?: response14 return modifiedResponse15 } catch(error: FuelError) {16 if (error.exception as? InterruptedIOException != null) {17 interruptCallback?.invoke(request)18 }19 throw error20 }21 }22}...

Full Screen

Full Screen

interrupt

Using AI Code Generation

copy

Full Screen

1fun getResponse(url: String) {2 val request = Fuel.get(url).response()3 request.join()4 val response = request.get()5 println(response)6}7suspend fun getResponseSuspend(url: String) {8 val response = Fuel.get(url).awaitStringResponse()9 println(response)10}11suspend fun getResponseSuspend2(url: String) {12 val response = url.httpGet().awaitStringResponse()13 println(response)14}15suspend fun getResponseSuspend3(url: String) {16 val (request, response, result) = url.httpGet().awaitStringResponseResult()17 println(result)18}19suspend fun getResponseSuspend4(url: String) {20 val (request, response, result) = url.httpGet().awaitStringResult()21 println(result)22}23suspend fun getResponseSuspend5(url: String) {24 val result = url.httpGet().awaitString()25 println(result)26}27suspend fun getResponseSuspend6(url: String) {28 val (request, response, result) = url.httpGet().awaitStringResult()29 println(result)30}31suspend fun getResponseSuspend7(url: String) {32 val result = url.httpGet().awaitString()33 println(result)34}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful