How to use String.httpDelete method of com.github.kittinunf.fuel.Fuel class

Best Fuel code snippet using com.github.kittinunf.fuel.Fuel.String.httpDelete

SessionTest.kt

Source:SessionTest.kt Github

copy

Full Screen

1import com.beust.klaxon.JsonReader2import com.beust.klaxon.Klaxon3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.fuel.httpDelete7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.httpDelete9import com.github.kittinunf.result.Result10import config.ConfigLoader11import config.Services12import model.*13import org.junit.After14import org.junit.AfterClass15import org.junit.Assert.assertTrue16import org.junit.BeforeClass17import org.junit.Test18import process.MicroServiceManager19import utils.KlaxonDate20import utils.dateConverter21import utils.toJson22import java.io.StringReader23import java.util.*24import java.util.concurrent.CountDownLatch25class SessionTest {26 private var killFunction: () -> Any = {}27 companion object {28 private val startArguments = arrayOf("0")29 private val manager = MicroServiceManager()30 private lateinit var baseUrl: String31 private lateinit var wsClient: WSClient32 private var sessionList = mutableListOf<SessionDNS>()33 private lateinit var latch: CountDownLatch34 @BeforeClass35 @JvmStatic36 fun setUp() {37 ConfigLoader().load(startArguments)38 baseUrl = Services.Utils.defaultHostUrlSession(Services.SESSION) + "/"+ Params.Session.API_NAME39 println("istanzio sessionList")40 manager.newService(Services.SESSION, startArguments[0]) // 850041 Thread.sleep(3000)42 wsClient = object : WSClient(URIFactory.getSessionURI(port = 8501)) {43 override fun onMessage(message: String) {44 super.onMessage(message)45 val sessionWrapper = Serializer.klaxon.fieldConverter(KlaxonDate::class, dateConverter).parse<PayloadWrapper>(message)46 sessionList.add(Serializer.klaxon.parse<SessionDNS>(sessionWrapper!!.body)47 ?: SessionDNS(-1, "no", -1,"emptyLeaderCF").also { println("NON HO INIZIALIZZATO LA SESSION PERCHè NON HO CAPITO IL MESSAGGIO DELLA WS: $message") })48 latch.countDown()49 }50 }.also { WSClientInitializer.init(it) }51 }52 @AfterClass53 @JvmStatic54 fun closeConnection() {55 manager.closeSession(startArguments[0])56 }57 }58 @After59 fun killThemAll() {60 killFunction()61 killFunction = {}62 }63 @Test64 fun `create new session`() {65 sessionList.clear()66 latch = CountDownLatch(1)67 val patient = "gntlrt94b21g479u"68 val leader = "asdflkjasdflkj"69 wsClient.sendMessage(PayloadWrapper(-1, WSOperations.NEW_SESSION, SessionAssignment(patient, leader).toJson()).toJson())70 latch.await()71 Thread.sleep(3000)72 killFunction = {73 println(baseUrl)74 "$baseUrl/${sessionList.first().sessionId}".httpDelete().responseString()75 Thread.sleep(4000)76 }77 assertTrue(sessionList.first().patientCF == patient)78 }79 @Test80 fun `get all sessions list`() {81 handlingGetResponseWithArrayOfDnsSessions(makeGet(baseUrl))82 val previousSize = sessionList.size83 println(previousSize)84 latch = CountDownLatch(3)85 wsClient.sendMessage(PayloadWrapper(-1, WSOperations.NEW_SESSION, SessionAssignment("1", "-1").toJson()).toJson())86 Thread.sleep(500)87 wsClient.sendMessage(PayloadWrapper(-1, WSOperations.NEW_SESSION, SessionAssignment("2", "-1").toJson()).toJson())88 Thread.sleep(500)89 wsClient.sendMessage(PayloadWrapper(-1, WSOperations.NEW_SESSION, SessionAssignment("3", "-1").toJson()).toJson())90 latch.await()91 Thread.sleep(3000)92 handlingGetResponseWithArrayOfDnsSessions(makeGet(baseUrl))93 killFunction = {94 sessionList.takeLast(3).forEach {95 "$baseUrl/${it.sessionId}".httpDelete().responseString()96 Thread.sleep(500)97 }98 Thread.sleep(4000)99 }100 println(sessionList.size)101 assertTrue(sessionList.size == previousSize + 3)102 }103 @Test104 fun `close session`() {105 latch = CountDownLatch(1)106 wsClient.sendMessage(PayloadWrapper(-1, WSOperations.NEW_SESSION, SessionAssignment("1", "-1").toJson()).toJson())107 latch.await()108 handlingGetResponseWithArrayOfDnsSessions(makeGet(baseUrl))109 val sessionId = sessionList.first().sessionId110 val previousSize = sessionList.size111 "$baseUrl/$sessionId".httpDelete().responseString()112 handlingGetResponseWithArrayOfDnsSessions(makeGet(baseUrl))113 assertTrue(sessionList.size == previousSize - 1)114 }115 private fun makeGet(string: String): Triple<Request, Response, Result<String, FuelError>> {116 return string.httpGet().responseString()117 }118 private fun handlingGetResponseWithArrayOfDnsSessions(triplet: Triple<Request, Response, Result<String, FuelError>>) {119 triplet.third.fold(success = {120 val klaxon = Klaxon()121 JsonReader(StringReader(it)).use { reader ->122 reader.beginArray {123 sessionList.clear()124 while (reader.hasNext()) {125 val session = klaxon.parse<SessionDNS>(reader)!!126 (sessionList as ArrayList<SessionDNS>).add(session)127 }128 }129 }130 }, failure = {131 println(String(it.errorData))132 })133 }134}...

Full Screen

Full Screen

TasksApi.kt

Source:TasksApi.kt Github

copy

Full Screen

1package org.hse.ataskmobileclient.apis2import android.util.Log3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult5import com.github.kittinunf.fuel.gson.jsonBody6import com.github.kittinunf.fuel.httpDelete7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.httpPost9import com.github.kittinunf.fuel.httpPut10import com.github.kittinunf.result.Result11import com.google.gson.Gson12import com.google.gson.reflect.TypeToken13import org.hse.ataskmobileclient.dto.GoogleImageDto14import org.hse.ataskmobileclient.dto.TaskDto15import org.hse.ataskmobileclient.models.Urls16import java.text.SimpleDateFormat17import java.util.*18import kotlin.collections.ArrayList19class TasksApi {20 private val sdf = SimpleDateFormat("yyyy-MM-dd")21 suspend fun createTask(22 token: String,23 taskDto: TaskDto,24 ) :TaskDto? {25 val (_, response, result) = Urls().getTaskUrl()26 .httpPost()27 .header("Authorization", "Bearer $token")28 .jsonBody(taskDto) // haven't checked if it is working29 .awaitStringResponseResult()30 val jsonBody = Gson().toJson(taskDto)31 Log.i(TAG, "Добавление задачи, тело запроса: $jsonBody")32 return result.fold(33 { data -> Gson().fromJson(data, TaskDto::class.java) },34 {35 Log.e(TAG, "Ошибка при создании задачи: ${it.exception.message}, ${response.statusCode}")36 return null37 }38 )39 }40 suspend fun deleteTask(41 token: String,42 taskDto: TaskDto,43 ) {44 val (_, response, result) = Urls().getTaskUrl(taskDto.uuid!!) // /task/{id}45 .httpDelete()46 .header("Authorization", "Bearer $token")47 .awaitStringResponseResult()48 return result.fold(49 { data -> Log.d(TAG, "Результат удаления: $data")},50 {51 Log.e(TAG, "Ошибка при удалении задачи: ${it.exception.message}, ${response.statusCode}")52 }53 )54 }55 suspend fun updateTask(56 token: String,57 taskDto: TaskDto,58 ) :TaskDto? {59 if (taskDto.uuid == null)60 return null61 val url = Urls().getTaskUrl(taskDto.uuid)62 val (_, response, result) = Urls().getTaskUrl(taskDto.uuid) // /task/{id}63 .httpPut()64 .header("Authorization", "Bearer $token")65 .jsonBody(taskDto) // haven't checked if it is working66 .awaitStringResponseResult()67 Log.d(TAG, url)68 return result.fold(69 { data -> Gson().fromJson(data, TaskDto::class.java) },70 {71 Log.e(TAG, "Ошибка при обновлении задачи: ${it.exception.message}, ${response.statusCode}")72 return null73 }74 )75 }76 suspend fun getAllTasks(token: String, startTime: Date?, endTime: Date?, label: String?): List<TaskDto> {77 val parameters = arrayListOf<Pair<String, Any?>>()78 if (startTime != null)79 parameters.add("dateFrom" to sdf.format(startTime))80 if (endTime != null)81 parameters.add("dateTo" to sdf.format(endTime))82 if (label != null)83 parameters.add("label" to label)84 val listType = object : TypeToken<ArrayList<TaskDto>?>() {}.type85 val (request, response, result) = Urls().getTaskUrl().httpGet(parameters)86 .header("Authorization", "Bearer $token")87 .awaitStringResponseResult()88 Log.i(TAG, "getAllTasks url=${request.url}")89 return result.fold(90 { data -> Gson().fromJson(data, listType) as ArrayList<TaskDto> },91 {92 Log.e(TAG, "Ошибка при запросе задач: ${it.exception.message}, ${response.statusCode}")93 return listOf()94 }95 )96 }97 private fun tasksResultHandler (98 result : Result<String, FuelError>,99 responseHandler: (result: ArrayList<TaskDto>) -> Unit?100 ) {101 when (result) {102 is Result.Failure -> {103 Log.i("ErrorMsg", result.getException().message ?: "")104 result.getException().stackTrace105 throw Exception(result.getException())106 }107 is Result.Success -> {108 val listType = object : TypeToken<ArrayList<TaskDto?>?>() {}.type109 val taskResult: ArrayList<TaskDto> = Gson().fromJson(result.get(), listType)110 responseHandler.invoke(taskResult)111 }112 }113 }114 companion object {115 private const val TAG = "TasksApi"116 }117}...

Full Screen

Full Screen

Client.kt

Source:Client.kt Github

copy

Full Screen

1package controller2import app.Config3import com.github.kittinunf.fuel.core.extensions.jsonBody4import com.github.kittinunf.fuel.httpDelete5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.fuel.json.FuelJson9import com.github.kittinunf.fuel.json.responseJson10import com.github.kittinunf.result.Result11import javafx.beans.property.SimpleStringProperty12import org.bouncycastle.jce.provider.BouncyCastleProvider13import tornadofx.*14import java.security.MessageDigest15import java.security.Security16import java.util.*17import javax.crypto.Cipher18import javax.crypto.spec.SecretKeySpec19open class ClientModule {20 lateinit var fetchRequest: ((String, String, p3: List<Pair<String, String>>?) -> FuelJson)21}22object Client {23 private val tokenProperty = SimpleStringProperty("")24 private var token by tokenProperty25 private lateinit var password: String26 fun settoken(t: String) { token = t }27 fun setpassword(p: String) { password = p }28 val Auth = AuthModule().apply { fetchRequest = ::fetchRequest }29 val Collections = CollectionsModule().apply { fetchRequest = ::fetchRequest }30 val Passwords = PasswordsModule().apply { fetchRequest = ::fetchRequest }31 private fun fetchRequest(path: String, _request: String, data: List<Pair<String, String>>? = null): FuelJson {32 val url = Config.url + path33 val request = when (_request) {34 "GET" -> url.httpGet()35 "POST" -> url.httpPost()36 "PUT" -> url.httpPut()37 "DELETE" -> url.httpDelete()38 else -> url.httpGet()39 }40 if (data != null) {41 val jsonData = with (JsonBuilder()) {42 for (p in data) {43 add(p.first, p.second)44 }45 build()46 }.toString()47 request.jsonBody(jsonData)48 }49 request.appendHeader(Pair("Authorization", token))50 val (_, response, result) = request.responseJson()51 if (result is Result.Failure) {52 var errStr: String53 if (response.statusCode == -1) {54 errStr = "{\"error\": \"${result.error.message}\"}"55 } else {56 errStr = String(response.data)57 }58 errStr = errStr.replace("\n", "")59 return FuelJson(errStr)60 }61 return result.get()62 }63 fun encryptIt(d: String): String {64 Security.addProvider(BouncyCastleProvider())65 val key = Base64.getEncoder().encodeToString(password.hashMe("SHA-256").toByteArray()).slice(0..31)66 val keyBytes: ByteArray = key.toByteArray(charset("UTF8"))67 val skey = SecretKeySpec(keyBytes, "AES")68 val input = d.toByteArray(charset("UTF8"))69 synchronized(Cipher::class.java) {70 val cipher = Cipher.getInstance("AES/ECB/PKCS7Padding")71 cipher.init(Cipher.ENCRYPT_MODE, skey)72 val cipherText = ByteArray(cipher.getOutputSize(input.size))73 var ctLength = cipher.update(74 input, 0, input.size,75 cipherText, 076 )77 ctLength += cipher.doFinal(cipherText, ctLength)78 return String(Base64.getEncoder().encode(cipherText))79 }80 }81 fun decryptIt(d: String): String {82 Security.addProvider(BouncyCastleProvider())83 val key = Base64.getEncoder().encodeToString(password.hashMe("SHA-256").toByteArray()).slice(0..31)84 val keyBytes = key.toByteArray(charset("UTF8"))85 val skey = SecretKeySpec(keyBytes, "AES")86 val input = org.bouncycastle.util.encoders.Base6487 .decode(d.trim { it <= ' ' }.toByteArray(charset("UTF8")))88 synchronized(Cipher::class.java) {89 val cipher = Cipher.getInstance("AES/ECB/PKCS7Padding")90 cipher.init(Cipher.DECRYPT_MODE, skey)91 val plainText = ByteArray(cipher.getOutputSize(input.size))92 var ptLength = cipher.update(input, 0, input.size, plainText, 0)93 ptLength += cipher.doFinal(plainText, ptLength)94 return String(plainText).trim { it <= ' ' }95 }96 }97}98fun String.hashMe(algo: String): String {99 val bytes = this.toByteArray()100 val md = MessageDigest.getInstance(algo)101 val digest = md.digest(bytes)102 return digest.fold("") { str, it -> str + "%02x".format(it) }103}...

Full Screen

Full Screen

Http.kt

Source:Http.kt Github

copy

Full Screen

1package com.fileee.oihAdapter.interpreter2import arrow.Kind3import arrow.core.Try4import arrow.core.left5import arrow.core.right6import arrow.effects.typeclasses.Async7import arrow.effects.typeclasses.milliseconds8import arrow.effects.typeclasses.seconds9import arrow.typeclasses.binding10import arrow.typeclasses.bindingCatch11import com.fileee.oihAdapter.Schedule12import com.fileee.oihAdapter.algebra.*13import com.github.kittinunf.fuel.core.FuelError14import com.github.kittinunf.fuel.core.Request15import com.github.kittinunf.fuel.core.Response16import com.github.kittinunf.fuel.httpDelete17import com.github.kittinunf.fuel.httpGet18import com.github.kittinunf.fuel.httpPost19import com.github.kittinunf.fuel.httpPut20import com.github.kittinunf.result.Result21typealias HttpFuelResp = Triple<Request, Response, Result<String, FuelError>>22/**23 * Interpreter for [HttpAlgebra]. This raises the constraint for [M] from [Monad] to [Async]. [Async] models24 * asynchronous behaviour and is a requirement for [Schedule].25 */26class HttpInterpreter<F>(27 val logAlgebra: LogAlgebra<F>,28 override val M: Async<F>29) : HttpAlgebra<F> {30 /**31 * Handles responses from Fuel, the http library used and retries for a certain amount of time on specific errors.32 *33 * @param tr A function to try and run which produces a [HttpFuelResp]34 */35 internal fun handleFuelResponse(tr: () -> Kind<F, HttpFuelResp>): Kind<F, HttpResponse> = M.bindingCatch {36 // below schedule equates to exponential backoff with the power of 2 and a base of 10ms till it reaches37 // 60 seconds, then it continues with one retry per minute up to five times38 Schedule.exponential(10.milliseconds).whileValue { it.lte(60.seconds) }39 .andThen(Schedule.spaced(60.seconds) * 5)40 // run the schedule with tr until it succeeds or the schedule ends41 .runS(M, tr).attempt().bind()42 .fold({ HttpException.UnhandledException(it).left() }, { (_, resp, res) ->43 res.fold({44 HttpResult(resp.statusCode, it).right()45 }, {46 HttpResult(resp.statusCode, it.response.responseMessage).right()47 })48 })49 }50 /**51 * Transforms a [Try<HttpFuelResp>] to a [Kind<F, HttpFuelResponse>] where [F] has an instance of [MonadError]52 * (which [Async] is extends)53 *54 * Raises errors for all retry-able error cases (Unhandled errors, usually connection issues), and rate-limit or service55 * unavailable error codes.56 * Everything else is accepted as either finished or non-retry-able.57 */58 internal fun Try<HttpFuelResp>.raiseRetryErrors() = fold({59 M.raiseError<HttpFuelResp>(it)60 }, { resp ->61 when (resp.second.statusCode) {62 403, 401 -> M.just(resp)63 429 -> M.raiseError(Exception("Rate limit reached"))64 503, 504 -> M.raiseError(Exception("Service unavailable"))65 else -> M.just(resp)66 }67 })68 override fun httpGet(path: String, headers: Map<String, String>): Kind<F, HttpResponse> =69 handleFuelResponse {70 M.binding {71 logAlgebra.debug("HttpGet to $path").bind()72 Try {73 path.httpGet()74 .header(headers)75 .responseString()76 }.raiseRetryErrors().bind()77 }78 }79 override fun httpPost(path: String, headers: Map<String, String>, body: String): Kind<F, HttpResponse> =80 handleFuelResponse {81 M.binding {82 logAlgebra.debug("HttpPost to $path").bind()83 Try {84 path.httpPost()85 .body(body)86 .header(headers + mapOf("Content-Type" to "application/json"))87 .responseString()88 }.raiseRetryErrors().bind()89 }90 }91 override fun httpPut(path: String, headers: Map<String, String>, body: String): Kind<F, HttpResponse> =92 handleFuelResponse {93 M.binding {94 logAlgebra.debug("HttpPut to $path").bind()95 Try {96 path.httpPut()97 .body(body)98 .header(headers + mapOf("Content-Type" to "application/json"))99 .responseString()100 }.raiseRetryErrors().bind()101 }102 }103 override fun httpDelete(path: String, headers: Map<String, String>): Kind<F, HttpResponse> =104 handleFuelResponse {105 M.binding {106 logAlgebra.debug("HttpDelete to $path").bind()107 Try {108 path.httpDelete()109 .header(headers)110 .responseString()111 }.raiseRetryErrors().bind()112 }113 }114}...

Full Screen

Full Screen

GMNetService.kt

Source:GMNetService.kt Github

copy

Full Screen

1package com.thierry.beaconfire.service2import android.content.Intent3import android.support.v4.content.LocalBroadcastManager4import android.util.Log5import android.webkit.CookieManager6import com.github.kittinunf.fuel.android.extension.responseJson7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.httpDelete9import com.github.kittinunf.fuel.httpGet10import com.github.kittinunf.fuel.httpPost11import com.github.kittinunf.fuel.httpPut12import com.github.kittinunf.fuel.core.Manager13import com.thierry.beaconfire.App14import com.thierry.beaconfire.util.Constants15import org.jetbrains.anko.custom.async16import org.jetbrains.anko.uiThread17/** @brief Http状态枚举 */18enum class HttpStatusCode(val code: Int) {19 HttpStatusCodeSuccess(200),20 HttpStatusCodeError(500),21 HttpStatusCodeUnauthorized(403)22};23/** @brief Http方法枚举 */24enum class HttpMethod {25 HttpMethodGet,26 HttpMethodPost,27 HttpMethodPut,28 HttpMethodDelete,29};30/**31 * Created by Thierry on 16/2/25.32 */33class GMNetService private constructor() {34 val localBroadcastManager = LocalBroadcastManager.getInstance(App.instance);35 val cookieManager: CookieManager = CookieManager.getInstance()36 val TAG = GMNetService::class.java.canonicalName37 var apiHost: String = Constants.Host38 private object Holder {39 val INSTANCE = GMNetService()40 }41 companion object {42 val instance: GMNetService by lazy { Holder.INSTANCE }43 }44 fun doRequest(remoteUrl: String, method: HttpMethod, params: List<Pair<String, Any?>>?, success: (Response) -> Unit, failed: (String) -> Unit) {45 Log.d(TAG, remoteUrl)46 async {47 Manager.instance.baseHeaders = mapOf("Cookie" to cookieManager.getCookie(apiHost))48 when (method) {49 HttpMethod.HttpMethodGet ->50 remoteUrl.httpGet(params).responseJson { _, response, _ ->51 uiThread {52 handleResponse(response, success, failed)53 }54 }55 HttpMethod.HttpMethodPost ->56 remoteUrl.httpPost(params).responseJson { _, response, _ ->57 uiThread {58 handleResponse(response, success, failed)59 }60 }61 HttpMethod.HttpMethodDelete ->62 remoteUrl.httpDelete(params).responseJson { _, response, _ ->63 uiThread {64 handleResponse(response, success, failed)65 }66 }67 HttpMethod.HttpMethodPut ->68 remoteUrl.httpPut(params).responseJson { request, response, result ->69 uiThread {70 handleResponse(response, success, failed)71 }72 }73 }74 }75 }76 fun handleResponse(response: Response, success: (Response) -> Unit, failed: (String) -> Unit) {77 Log.d(TAG, "handleResponse")78 val statusCode = response.httpStatusCode79 if (statusCode == HttpStatusCode.HttpStatusCodeSuccess.code) {80 success(response)81 } else if (statusCode == HttpStatusCode.HttpStatusCodeUnauthorized.code) {82 Log.d(TAG, "HttpStatusCode.HttpStatusCodeUnauthorized")83 this.sendLoginExpired()84 } else {85 failed("Request Data Error")86 }87 }88 fun sendLoginExpired() {89 val intent: Intent = Intent()90 intent.action = Constants.Broadcast.LoginExpired91 localBroadcastManager.sendBroadcast(intent)92 }93}...

Full Screen

Full Screen

KtorExercises1.kt

Source:KtorExercises1.kt Github

copy

Full Screen

1package lodz.jug.kotlin.ktorwork.one.exercises2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.fuel.httpDelete5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.result.Result9import com.google.gson.Gson10import io.kotlintest.shouldBe11import org.amshove.kluent.`should contain`12import org.amshove.kluent.shouldBeEqualTo13import org.amshove.kluent.shouldBeInstanceOf14import org.amshove.kluent.shouldEqualTo15import org.assertj.core.internal.bytebuddy.utility.RandomString16import org.junit.Test17class KtorExercises1 {18 @Test19 fun `should put number`() {20 val (_, response, result: Result<String, FuelError>) = "http://localhost:${KtorExercises1Server.serverPort}/addNumber/2"21 .httpPost().responseString()22 response.statusCode shouldEqualTo (200)23 result shouldBeInstanceOf (Result.Success::class)24 result.get() shouldBeEqualTo ("added number 2")25 }26 @Test27 fun `default 404 page should be defined`() {28 repeat(5) {29 val random = RandomString.make(5)30 val (_, response: Response, _) = "http://localhost:${KtorExercises1Server.serverPort}/$random"31 .httpPost().response()32 response.statusCode shouldEqualTo 40433 String(response.data) shouldBeEqualTo "try again later"34 }35 }36 @Test37 fun `returns BadRequest when number can not be parsed`() {38 repeat(5) {39 val random = RandomString.make(5)40 val (_, response: Response, _) = "http://localhost:${KtorExercises1Server.serverPort}/addNumber/$random"41 .httpPost().responseString()42 response.statusCode shouldEqualTo 40043 String(response.data) `should contain` "unable to retrieve parameter"44 }45 }46 @Test47 fun `removes all data`(){48 val (_, response, result) = "http://localhost:${KtorExercises1Server.serverPort}/all"49 .httpDelete().responseString()50 response.statusCode shouldEqualTo 20051 result.get() shouldBe "all data removed!!!"52 }53 @Test54 fun `stores and retrieves numbers`() {55 //given56 "http://localhost:${KtorExercises1Server.serverPort}/all".httpDelete().response()57 (1 .. 5).map {58 val (_, response: Response, _) = "http://localhost:${KtorExercises1Server.serverPort}/addNumber/$it"59 .httpPost().response()60 response.statusCode shouldEqualTo 20061 }62 val (_, response, result) = "http://localhost:${KtorExercises1Server.serverPort}/numbers"63 .httpGet().responseString()64 response.statusCode shouldBe 20065 result.get() shouldBe """{"numbers":[1,2,3,4,5]}"""66 }67 data class InitRequest(val numbers:List<Int>)68 @Test69 fun `send and receive json`() {70 val payload=Gson().toJson(InitRequest(listOf(10,11,12)))71 val (_, resetResponse,resetResult)="http://localhost:${KtorExercises1Server.serverPort}/reset"72 .httpPut().jsonBody(payload).responseString()73 resetResponse.statusCode shouldBe 20074 resetResult.get() shouldBe "database reset"75 val (_, selectAll, selectAllResult) = "http://localhost:${KtorExercises1Server.serverPort}/numbers"76 .httpGet().responseString()77 selectAll.statusCode shouldBe 20078 selectAllResult.get() shouldBe """{"numbers":[10,11,12]}"""79 }80}...

Full Screen

Full Screen

KtorAnswers1.kt

Source:KtorAnswers1.kt Github

copy

Full Screen

1package lodz.jug.kotlin.ktorwork.one.answers2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.fuel.httpDelete5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.result.Result9import com.google.gson.Gson10import io.kotlintest.shouldBe11import org.amshove.kluent.`should contain`12import org.amshove.kluent.shouldBeEqualTo13import org.amshove.kluent.shouldBeInstanceOf14import org.amshove.kluent.shouldEqualTo15import org.assertj.core.internal.bytebuddy.utility.RandomString16import org.junit.Test17class KtorAnswers1 {18 @Test19 fun `should put number`() {20 val (_, response, result: Result<String, FuelError>) = "http://localhost:${KtorAnswers1Server.serverPort}/addNumber/2"21 .httpPost().responseString()22 response.statusCode shouldEqualTo (200)23 result shouldBeInstanceOf (Result.Success::class)24 result.get() shouldBeEqualTo ("added number 2")25 }26 @Test27 fun `default 404 page should be defined`() {28 repeat(5) {29 val random = RandomString.make(5)30 val (_, response: Response, _) = "http://localhost:${KtorAnswers1Server.serverPort}/$random"31 .httpPost().response()32 response.statusCode shouldEqualTo 40433 String(response.data) shouldBeEqualTo "try again later"34 }35 }36 @Test37 fun `returns BadRequest when number can not be parsed`() {38 repeat(5) {39 val random = RandomString.make(5)40 val (_, response: Response, _) = "http://localhost:${KtorAnswers1Server.serverPort}/addNumber/$random"41 .httpPost().responseString()42 response.statusCode shouldEqualTo 40043 String(response.data) `should contain` "unable to retrieve parameter"44 }45 }46 @Test47 fun `removes all data`(){48 val (_, response, result) = "http://localhost:${KtorAnswers1Server.serverPort}/all"49 .httpDelete().responseString()50 response.statusCode shouldEqualTo 20051 result.get() shouldBe "all data removed!!!"52 }53 @Test54 fun `stores and retrieves numbers`() {55 //given56 "http://localhost:${KtorAnswers1Server.serverPort}/all".httpDelete().response()57 (1 .. 5).map {58 val (_, response: Response, _) = "http://localhost:${KtorAnswers1Server.serverPort}/addNumber/$it"59 .httpPost().response()60 response.statusCode shouldEqualTo 20061 }62 val (_, response, result) = "http://localhost:${KtorAnswers1Server.serverPort}/numbers"63 .httpGet().responseString()64 response.statusCode shouldBe 20065 result.get() shouldBe """{"numbers":[1,2,3,4,5]}"""66 }67 data class InitRequest(val numbers:List<Int>)68 @Test69 fun `send and receive json`() {70 val payload=Gson().toJson(InitRequest(listOf(10,11,12)))71 val (_, resetResponse,resetResult)="http://localhost:${KtorAnswers1Server.serverPort}/reset"72 .httpPut().jsonBody(payload).responseString()73 resetResponse.statusCode shouldBe 20074 resetResult.get() shouldBe "database reset"75 val (_, selectAll, selectAllResult) = "http://localhost:${KtorAnswers1Server.serverPort}/numbers"76 .httpGet().responseString()77 selectAll.statusCode shouldBe 20078 selectAllResult.get() shouldBe """{"numbers":[10,11,12]}"""79 }80}...

Full Screen

Full Screen

RestAPI.kt

Source:RestAPI.kt Github

copy

Full Screen

1package org.intellij.plugin.zeppelin.api.remote.rest2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.fuel.httpDelete5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.fuel.moshi.responseObject9import com.github.kittinunf.result.Result10import org.intellij.plugin.zeppelin.utils.JsonParser11open class RestAPI(host: String, port: Int, https: Boolean = false) {12 private val protocol: String = if (https) "https" else "http"13 private val apiUrl: String = "$protocol://$host:$port/api"14 fun performGetRequest(uri: String,15 credentials: String?): RestResponseMessage {16 val headers = credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap()17 val (_, _, result) = "$apiUrl$uri".httpGet()18 .header(headers)19 .timeout(10000)20 .responseObject<RestResponseMessage>()21 return getResponse(result)22 }23 fun performPostData(uri: String, data: Map<String, Any>, credentials: String?): RestResponseMessage {24 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/json").plus(25 credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap())26 val (_, _, result) = "$apiUrl$uri".httpPost()27 .header(headers)28 .body(JsonParser.toJson(data))29 .timeout(10000)30 .responseObject<RestResponseMessage>()31 return getResponse(result)32 }33 fun performDeleteData(uri: String, credentials: String?): RestResponseMessage {34 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/json").plus(35 credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap())36 val (_, _, result) = "$apiUrl$uri".httpDelete()37 .header(headers)38 .timeout(10000)39 .responseObject<RestResponseMessage>()40 return getResponse(result)41 }42 fun performPostForm(uri: String, params: Map<String, String>): Pair<Response, RestResponseMessage> {43 val paramString = "?" + params.map { it.key + "=" + it.value }.joinToString("&")44 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/x-www-form-urlencoded")45 val (_, response, result) = "$apiUrl$uri$paramString".httpPost()46 .header(headers)47 .timeout(10000)48 .responseObject<RestResponseMessage>()49 return Pair(response, getResponse(result))50 }51 fun performPutData(uri: String, data: Map<String, Any>,52 credentials: String?): RestResponseMessage {53 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/json").plus(54 credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap())55 val (_, _, result) = "$apiUrl$uri".httpPut()56 .header(headers)57 .body(JsonParser.toJson(data))58 .timeout(10000)59 .responseObject<RestResponseMessage>()60 return getResponse(result)61 }62 private fun getResponse(63 result: Result<RestResponseMessage, FuelError>): RestResponseMessage {64 val (obj, errors) = result65 if (errors != null) {66 throw errors67 }68 return obj!!69 }70}71data class RestResponseMessage(val status: String, val message: String, val body: Any = Any())...

Full Screen

Full Screen

String.httpDelete

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.Fuel2fun main(args: Array<String>) {3 println("request: $request")4 println("response: $response")5 println("result: $result")6}7result: Success(data: {8 "args": {}, 9 "files": {}, 10 "form": {}, 11 "headers": {12 },

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