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

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

FirebaseRestClient.kt

Source:FirebaseRestClient.kt Github

copy

Full Screen

1package dev.mfazio.tworooms.restclient2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.httpDelete4import com.github.kittinunf.fuel.httpGet5import com.github.kittinunf.fuel.httpPatch6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.result.Result8import com.google.auth.oauth2.AccessToken9import com.google.auth.oauth2.GoogleCredentials10import com.google.firebase.auth.UserRecord11import dev.mfazio.tworooms.restclient.types.*12import dev.mfazio.tworooms.types.*13import kotlinx.serialization.json.Json14import kotlinx.serialization.json.JsonConfiguration15import java.time.OffsetDateTime16import java.time.format.DateTimeFormatter17import java.util.*18import kotlin.math.floor19import kotlin.random.Random20class FirebaseRestClient(credentials: GoogleCredentials, collectionId: String) {21 private val json = Json(context = ValueObject.valueObjectModule)22 private val scoped: GoogleCredentials = credentials.createScoped("https://www.googleapis.com/auth/datastore")23 private var accessToken: AccessToken24 init {25 //TODO: How often do I need to do this?26 this.accessToken = scoped.refreshAccessToken()27 }28 private val baseAPIUrl =29 "https://firestore.googleapis.com/v1/projects/tworooms-66ba8/databases/(default)/documents/$collectionId"30 fun findGame(gameCode: String): FirebaseRestResponse<FirebaseDocument> {31 checkAccessToken()32 val (request, response, result) = "$baseAPIUrl/$gameCode"33 .httpGet()34 .header("Authorization", "Bearer ${accessToken.tokenValue}")35 .responseString()36 val (responseString, error) = result37 return FirebaseRestResponse(38 if (responseString != null) {39 json.parse(FirebaseDocument.serializer(), responseString)40 } else null,41 error42 )43 }44 fun getPlayersForGame(gameCode: String): FirebaseRestResponse<List<FirebaseDocument>> {45 checkAccessToken()46 val (request, response, result) = "$baseAPIUrl/$gameCode/players"47 .httpGet()48 .header("Authorization", "Bearer ${accessToken.tokenValue}")49 .responseString()50 val (responseString, error) = result51 val documentsList = json.parse(FirebaseDocumentList.serializer(), responseString ?: "")52 return FirebaseRestResponse(53 documentsList.documents,54 error55 )56 }57 fun createGame(user: UserRecord, roles: List<TwoRoomsRole>): FirebaseRestResponse<String> {58 checkAccessToken()59 //TODO: Wrap this in a transaction - https://cloud.google.com/firestore/docs/reference/rest/#rest-resource:-v1.projects.databases.documents60 var gameCode: String = ""61 do {62 gameCode = TwoRoomsGame.generateGameCode()63 val existingGameResponse = findGame(gameCode)64 } while (existingGameResponse.data != null)65 val body = json.stringify(66 FirebaseDocument.serializer(),67 FirebaseDocument(68 fields = mapOf(69 "gameCode" to StringValueObject(gameCode),70 "ownerUID" to StringValueObject(user.uid),71 "status" to StringValueObject(GameStatus.Created.name),72 "roundNumber" to IntegerValueObject(1),73 "roundEndDateTime" to StringValueObject(""),74 "roles" to ArrayValueObject(ValueObjectArray(roles.map { StringValueObject(it.name) }))75 )76 )77 )78 val (request, response, result) = "$baseAPIUrl?documentId=$gameCode"79 .httpPost()80 .header("Authorization", "Bearer ${accessToken.tokenValue}")81 .body(body)82 .responseString()83 val (responseString, error) = result84 if (error == null) {85 val (addUserResponse, addUserError) = addUserToGame(gameCode, user)86 //TODO: Do something with the result?87 return FirebaseRestResponse(88 gameCode,89 addUserError90 )91 }92 return FirebaseRestResponse(93 gameCode,94 error95 )96 }97 fun joinGame(user: UserRecord, gameCode: String): FirebaseRestResponse<String?> {98 checkAccessToken()99 val existingGame = findGame(gameCode)100 return if (existingGame.wasSuccessful()) {101 val (result, fuelError) = addUserToGame(gameCode, user)102 FirebaseRestResponse(103 result,104 fuelError105 )106 } else {107 FirebaseRestResponse(108 "Game not found",109 existingGame.error110 )111 }112 }113 fun addUserToGame(gameCode: String, user: UserRecord): Result<String, FuelError> =114 addUserToGame(gameCode, user.displayName, user.uid)115 fun addMultipleRandomPlayers(gameCode: String, playerCount: Int? = null): Result<String, FuelError> {116 val count = playerCount ?: Random.nextInt(4, 12)117 val results = (1..count).map { _ ->118 val name = ((65..90) + (97..122))119 .map { it.toChar().toString() }120 .shuffled()121 .take(Random.nextInt(4, 12))122 .joinToString("")123 val result = addUserToGame(gameCode, name, UUID.randomUUID().toString())124 if (result.component2() != null) return result125 result126 }127 return results.last()128 }129 private fun addUserToGame(gameCode: String, name: String, uid: String): Result<String, FuelError> {130 checkAccessToken()131 val body = json.stringify(132 FirebaseDocument.serializer(),133 FirebaseDocument(134 fields = mapOf(135 "name" to StringValueObject(name),136 "uid" to StringValueObject(uid)137 )138 )139 )140 val (request, response, result) = "$baseAPIUrl/$gameCode/players?documentId=${uid}"141 .httpPost()142 .header("Authorization", "Bearer ${accessToken.tokenValue}")143 .body(body)144 .responseString()145 return result146 }147 fun removePlayer(gameCode: String, uid: String): Result<String, FuelError> {148 checkAccessToken()149 val (request, response, result) = "$baseAPIUrl/$gameCode/players/${uid}"150 .httpDelete()151 .header("Authorization", "Bearer ${accessToken.tokenValue}")152 .responseString()153 return result154 }155 fun startGame(game: TwoRoomsGame): Result<String, FuelError> {156 checkAccessToken()157 val distributedPlayers = distributeTeams(game)158 //TODO: Make this all a single transaction.159 distributedPlayers.forEach { player ->160 val body = json.stringify(161 FirebaseDocument.serializer(),162 FirebaseDocument(163 fields = mapOf(164 "name" to StringValueObject(player.name),165 "uid" to StringValueObject(player.uid),166 "team" to StringValueObject(player.team?.name),167 "role" to StringValueObject(player.role?.name)168 )169 )170 )171 val (request, response, result) =172 "$baseAPIUrl/${game.gameCode}/players/${player.uid}"173 .httpPatch()174 .body(body)175 .header("Authorization", "Bearer ${accessToken.tokenValue}")176 .responseString()177 val (resultString, fuelError) = result178 if (fuelError != null) {179 return result180 }181 }182 return this.updateGameStatus(game.gameCode, GameStatus.Started)183 }184 fun endGame(gameCode: String): Result<String, FuelError> = this.updateGameStatus(gameCode, GameStatus.Ended)185 fun cancelGame(gameCode: String): Result<String, FuelError> = this.updateGameStatus(gameCode, GameStatus.Canceled)186 fun startRound(game: TwoRoomsGame, roundNumber: Int): Result<String, FuelError> {187 checkAccessToken()188 val body = json.stringify(189 FirebaseDocument.serializer(),190 FirebaseDocument(191 fields = mapOf(192 "roundEndDateTime" to StringValueObject(193 OffsetDateTime.now().plusMinutes((4 - roundNumber).toLong())194 .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)195 )196 )197 )198 )199 val (request, response, result) =200 "$baseAPIUrl/${game.gameCode}?updateMask.fieldPaths=roundEndDateTime"201 .httpPatch()202 .body(body)203 .header("Authorization", "Bearer ${accessToken.tokenValue}")204 .responseString()205 return result206 }207 fun nextRound(game: TwoRoomsGame, roundNumber: Int): Result<String, FuelError> {208 checkAccessToken()209 val body = json.stringify(210 FirebaseDocument.serializer(),211 FirebaseDocument(212 fields = mapOf(213 "roundNumber" to IntegerValueObject(roundNumber + 1),214 "roundEndDateTime" to StringValueObject("")215 )216 )217 )218 val (request, response, result) =219 "$baseAPIUrl/${game.gameCode}?updateMask.fieldPaths=roundNumber&updateMask.fieldPaths=roundEndDateTime"220 .httpPatch()221 .body(body)222 .header("Authorization", "Bearer ${accessToken.tokenValue}")223 .responseString()224 return result225 }226 fun pickWinners(game: TwoRoomsGame, winners: List<TwoRoomsTeam>): Result<String, FuelError> {227 checkAccessToken()228 val body = json.stringify(229 FirebaseDocument.serializer(),230 FirebaseDocument(231 fields = mapOf(232 "winners" to ArrayValueObject(ValueObjectArray(winners.map { StringValueObject(it.name) }))233 )234 )235 )236 val (request, response, result) =237 "$baseAPIUrl/${game.gameCode}?updateMask.fieldPaths=winners"238 .httpPatch()239 .body(body)240 .header("Authorization", "Bearer ${accessToken.tokenValue}")241 .responseString()242 return result243 }244 private fun updateGameStatus(gameCode: String, status: GameStatus): Result<String, FuelError> {245 checkAccessToken()246 val body = json.stringify(247 FirebaseDocument.serializer(),248 FirebaseDocument(fields = mapOf("status" to StringValueObject(status.name)))249 )250 val (request, response, result) =251 "$baseAPIUrl/${gameCode}?updateMask.fieldPaths=status"252 .httpPatch()253 .body(body)254 .header("Authorization", "Bearer ${accessToken.tokenValue}")255 .responseString()256 return result257 }258 private fun checkAccessToken() {259 if (this.accessToken.expirationTime?.before(Date()) != false) {260 this.accessToken = scoped.refreshAccessToken()261 }262 }263 private fun distributeTeams(game: TwoRoomsGame): List<TwoRoomsPlayer> =264 game.players.filterNotNull().shuffled().let { allPlayers ->265 val gambler =266 (if (allPlayers.count() % 2 != 0) allPlayers.first() else null)?.copy(267 team = TwoRoomsTeam.Gray,268 role = TwoRoomsRole.Gambler269 )270 val notRequiredRoles = game.roles.filter { !it.isRequired }271 val updatedPlayers = allPlayers272 .filter { it.uid != gambler?.uid }273 .mapIndexed { ind, player ->274 val roleInd = floor(ind / 2.0).toInt() - 1275 player.copy(276 team = if (ind % 2 == 0) TwoRoomsTeam.Blue else TwoRoomsTeam.Red,277 role = when {278 ind == 0 -> TwoRoomsRole.President279 ind == 1 -> TwoRoomsRole.Bomber280 roleInd < notRequiredRoles.count() -> notRequiredRoles[roleInd]281 else -> if (ind % 2 == 0) TwoRoomsRole.BlueTeam else TwoRoomsRole.RedTeam282 }283 )284 }285 (updatedPlayers + gambler).filterNotNull()286 }287 /*companion object {288 private val firebaseDocumentGson = GsonBuilder()289 .registerTypeAdapter(ValueObject::class.java, ValueObjectDeserializer())290 .create()291 }*/292}...

Full Screen

Full Screen

MainActivity.kt

Source:MainActivity.kt Github

copy

Full Screen

1package com.example.fuel2import android.os.Bundle3import android.os.Handler4import android.util.Log5import androidx.appcompat.app.AppCompatActivity6import com.github.kittinunf.fuel.Fuel7import com.github.kittinunf.fuel.core.Method8import com.github.kittinunf.fuel.core.FuelError9import com.github.kittinunf.fuel.core.FileDataPart10import com.github.kittinunf.fuel.core.FuelManager11import com.github.kittinunf.fuel.core.ResponseDeserializable12import com.github.kittinunf.fuel.core.extensions.authentication13import com.github.kittinunf.fuel.core.extensions.cUrlString14import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult15import com.github.kittinunf.fuel.gson.responseObject16import com.github.kittinunf.fuel.httpDelete17import com.github.kittinunf.fuel.httpGet18import com.github.kittinunf.fuel.httpPost19import com.github.kittinunf.fuel.httpPut20import com.github.kittinunf.fuel.livedata.liveDataObject21import com.github.kittinunf.fuel.rx.rxObject22import com.github.kittinunf.fuel.stetho.StethoHook23import com.github.kittinunf.result.Result24import com.google.gson.Gson25import com.google.gson.reflect.TypeToken26import io.reactivex.android.schedulers.AndroidSchedulers27import io.reactivex.disposables.CompositeDisposable28import io.reactivex.schedulers.Schedulers29import kotlinx.android.synthetic.main.activity_main.mainAuxText30import kotlinx.android.synthetic.main.activity_main.mainClearButton31import kotlinx.android.synthetic.main.activity_main.mainGoButton32import kotlinx.android.synthetic.main.activity_main.mainGoCoroutineButton33import kotlinx.android.synthetic.main.activity_main.mainResultText34import kotlinx.coroutines.CoroutineStart35import kotlinx.coroutines.Dispatchers36import kotlinx.coroutines.GlobalScope37import kotlinx.coroutines.launch38import java.io.File39import java.io.Reader40class MainActivity : AppCompatActivity() {41 private val TAG = MainActivity::class.java.simpleName42 private val bag by lazy { CompositeDisposable() }43 override fun onCreate(savedInstanceState: Bundle?) {44 super.onCreate(savedInstanceState)45 setContentView(R.layout.activity_main)46 FuelManager.instance.apply {47 basePath = "http://httpbin.org"48 baseHeaders = mapOf("Device" to "Android")49 baseParams = listOf("key" to "value")50 hook = StethoHook("Fuel Sample App")51// addResponseInterceptor { loggingResponseInterceptor() }52 }53 mainGoCoroutineButton.setOnClickListener {54 GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT) {55 executeCoroutine()56 }57 }58 mainGoButton.setOnClickListener {59 execute()60 }61 mainClearButton.setOnClickListener {62 mainResultText.text = ""63 mainAuxText.text = ""64 }65 }66 override fun onDestroy() {67 super.onDestroy()68 bag.clear()69 }70 private fun execute() {71 httpGet()72 httpPut()73 httpPost()74 httpPatch()75 httpDelete()76 httpDownload()77 httpUpload()78 httpBasicAuthentication()79 httpListResponseObject()80 httpResponseObject()81 httpGsonResponseObject()82 httpCancel()83 httpRxSupport()84 httpLiveDataSupport()85 }86 private suspend fun executeCoroutine() {87 httpGetCoroutine()88 }89 private suspend fun httpGetCoroutine() {90 val (request, response, result) = Fuel.get("/get", listOf("userId" to "123")).awaitStringResponseResult()91 Log.d(TAG, response.toString())92 Log.d(TAG, request.toString())93 update(result)94 }95 private fun httpCancel() {96 val request = Fuel.get("/delay/10")97 .interrupt { Log.d(TAG, it.url.toString() + " is interrupted") }98 .responseString { _, _, _ -> /* noop */ }99 Handler().postDelayed({ request.cancel() }, 1000)100 }101 private fun httpResponseObject() {102 "https://api.github.com/repos/kittinunf/Fuel/issues/1"103 .httpGet()104 .also { Log.d(TAG, it.cUrlString()) }105 .responseObject(Issue.Deserializer()) { _, _, result -> update(result) }106 }107 private fun httpListResponseObject() {108 "https://api.github.com/repos/kittinunf/Fuel/issues"109 .httpGet()110 .also { Log.d(TAG, it.cUrlString()) }111 .responseObject(Issue.ListDeserializer()) { _, _, result -> update(result) }112 }113 private fun httpGsonResponseObject() {114 "https://api.github.com/repos/kittinunf/Fuel/issues/1"115 .httpGet()116 .also { Log.d(TAG, it.cUrlString()) }117 .responseObject<Issue> { _, _, result -> update(result) }118 }119 private fun httpGet() {120 Fuel.get("/get", listOf("foo" to "foo", "bar" to "bar"))121 .also { Log.d(TAG, it.cUrlString()) }122 .responseString { _, _, result -> update(result) }123 "/get"124 .httpGet()125 .also { Log.d(TAG, it.cUrlString()) }126 .responseString { _, _, result -> update(result) }127 }128 private fun httpPut() {129 Fuel.put("/put", listOf("foo" to "foo", "bar" to "bar"))130 .also { Log.d(TAG, it.cUrlString()) }131 .responseString { _, _, result -> update(result) }132 "/put"133 .httpPut(listOf("foo" to "foo", "bar" to "bar"))134 .also { Log.d(TAG, it.cUrlString()) }135 .responseString { _, _, result -> update(result) }136 }137 private fun httpPost() {138 Fuel.post("/post", listOf("foo" to "foo", "bar" to "bar"))139 .also { Log.d(TAG, it.cUrlString()) }140 .responseString { _, _, result -> update(result) }141 "/post"142 .httpPost(listOf("foo" to "foo", "bar" to "bar"))143 .also { Log.d(TAG, it.cUrlString()) }144 .responseString { _, _, result -> update(result) }145 }146 private fun httpPatch() {147 val manager = FuelManager().apply {148 basePath = "http://httpbin.org"149 baseHeaders = mapOf("Device" to "Android")150 baseParams = listOf("key" to "value")151 }152 manager.forceMethods = true153 manager.request(Method.PATCH, "/patch", listOf("foo" to "foo", "bar" to "bar"))154 .also { Log.d(TAG, it.cUrlString()) }155 .responseString { _, _, result -> update(result) }156 }157 private fun httpDelete() {158 Fuel.delete("/delete", listOf("foo" to "foo", "bar" to "bar"))159 .also { Log.d(TAG, it.cUrlString()) }160 .responseString { _, _, result -> update(result) }161 "/delete"162 .httpDelete(listOf("foo" to "foo", "bar" to "bar"))163 .also { Log.d(TAG, it.cUrlString()) }164 .responseString { _, _, result -> update(result) }165 }166 private fun httpDownload() {167 val n = 100168 Fuel.download("/bytes/${1024 * n}")169 .fileDestination { _, _ -> File(filesDir, "test.tmp") }170 .progress { readBytes, totalBytes ->171 val progress = "$readBytes / $totalBytes"172 runOnUiThread { mainAuxText.text = progress }173 Log.v(TAG, progress)174 }175 .also { Log.d(TAG, it.toString()) }176 .responseString { _, _, result -> update(result) }177 }178 private fun httpUpload() {179 Fuel.upload("/post")180 .add {181 // create random file with some non-sense string182 val file = File(filesDir, "out.tmp")183 file.writer().use { writer ->184 repeat(100) {185 writer.appendln("abcdefghijklmnopqrstuvwxyz")186 }187 }188 FileDataPart(file)189 }190 .progress { writtenBytes, totalBytes ->191 Log.v(TAG, "Upload: ${writtenBytes.toFloat() / totalBytes.toFloat()}")192 }193 .also { Log.d(TAG, it.toString()) }194 .responseString { _, _, result -> update(result) }195 }196 private fun httpBasicAuthentication() {197 val username = "U$3|2|\\|@me"198 val password = "P@$\$vv0|2|)"199 Fuel.get("/basic-auth/$username/$password")200 .authentication()201 .basic(username, password)202 .also { Log.d(TAG, it.cUrlString()) }203 .responseString { _, _, result -> update(result) }204 "/basic-auth/$username/$password".httpGet()205 .authentication()206 .basic(username, password)207 .also { Log.d(TAG, it.cUrlString()) }208 .responseString { _, _, result -> update(result) }209 }210 private fun httpRxSupport() {211 val disposable = "https://api.github.com/repos/kittinunf/Fuel/issues/1"212 .httpGet()213 .rxObject(Issue.Deserializer())214 .subscribeOn(Schedulers.newThread())215 .observeOn(AndroidSchedulers.mainThread())216 .subscribe { result -> Log.d(TAG, result.toString()) }217 bag.add(disposable)218 }219 private fun httpLiveDataSupport() {220 "https://api.github.com/repos/kittinunf/Fuel/issues/1"221 .httpGet()222 .liveDataObject(Issue.Deserializer())223 .observeForever { result -> Log.d(TAG, result.toString()) }224 }225 private fun <T : Any> update(result: Result<T, FuelError>) {226 result.fold(success = {227 mainResultText.append(it.toString())228 }, failure = {229 mainResultText.append(String(it.errorData))230 })231 }232 data class Issue(233 val id: Int = 0,234 val title: String = "",235 val url: String = ""236 ) {237 class Deserializer : ResponseDeserializable<Issue> {238 override fun deserialize(reader: Reader) = Gson().fromJson(reader, Issue::class.java)!!239 }240 class ListDeserializer : ResponseDeserializable<List<Issue>> {241 override fun deserialize(reader: Reader): List<Issue> {242 val type = object : TypeToken<List<Issue>>() {}.type243 return Gson().fromJson(reader, type)244 }245 }246 }247}...

Full Screen

Full Screen

JournalpostApi.kt

Source:JournalpostApi.kt Github

copy

Full Screen

1package no.nav.dagpenger.journalføring.ferdigstill.adapter2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.extensions.authentication5import com.github.kittinunf.fuel.core.extensions.jsonBody6import com.github.kittinunf.fuel.httpPatch7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.result.Result9import com.squareup.moshi.Moshi10import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory11import mu.KotlinLogging12import no.nav.dagpenger.journalføring.ferdigstill.AdapterException13import no.nav.dagpenger.oidc.OidcClient14import java.util.regex.Pattern15private val logger = KotlinLogging.logger {}16internal interface JournalpostApi {17 fun ferdigstill(journalpostId: String)18 fun oppdater(journalpostId: String, jp: OppdaterJournalpostPayload)19}20internal data class OppdaterJournalpostPayload(21 val avsenderMottaker: Avsender,22 val bruker: Bruker,23 val tittel: String,24 val sak: Sak,25 val dokumenter: List<Dokument>,26 val behandlingstema: String = "ab0001",27 val tema: String = "DAG",28 val journalfoerendeEnhet: String = "9999"29)30internal enum class SaksType {31 GENERELL_SAK,32 FAGSAK33}34data class Bruker(val id: String, val idType: String = "FNR")35internal data class Sak(val saksType: SaksType, val fagsakId: String?, val fagsaksystem: String?)36internal data class Avsender(val navn: String)37internal data class Dokument(val dokumentInfoId: String, val tittel: String)38internal class JournalpostRestApi(private val url: String, private val oidcClient: OidcClient) :39 JournalpostApi {40 private val whitelistFeilmeldinger = setOf<String>(41 "Bruker kan ikke oppdateres for journalpost med journalpostStatus=J og journalpostType=I.",42 "er ikke midlertidig journalført",43 "er ikke midlertidig journalf&oslash;rt"44 )45 private val feilmelding: Pattern = Pattern.compile("\\(type=([^,]+), status=([^)]+)\\)\\.<\\/div><div>([^<]+)")46 val feilmeldingRegex = Regex("\\(type=([^,]+), status=([^)]+)\\)\\.<\\/div><div>([^<]+)")47 init {48 FuelManager.instance.forceMethods = true49 }50 companion object {51 private val moshiInstance = Moshi.Builder()52 .add(KotlinJsonAdapterFactory())53 .build()54 fun toJsonPayload(jp: OppdaterJournalpostPayload): String =55 moshiInstance.adapter<OppdaterJournalpostPayload>(56 OppdaterJournalpostPayload::class.java57 ).toJson(jp)58 }59 override fun oppdater(journalpostId: String, jp: OppdaterJournalpostPayload) {60 val (_, _, result) = retryFuel {61 url.plus("/rest/journalpostapi/v1/journalpost/$journalpostId")62 .httpPut()63 .authentication()64 .bearer(oidcClient.oidcToken().access_token)65 .jsonBody(66 toJsonPayload(67 jp68 )69 )70 .response()71 }72 when (result) {73 is Result.Success -> return74 is Result.Failure -> {75 if (sjekkTilstand(result, journalpostId)) return76 logger.error(77 "Feilet oppdatering av journalpost: $journalpostId, respons fra journalpostapi ${result.error.response}",78 result.error.exception79 )80 throw AdapterException(result.error.exception)81 }82 }83 }84 override fun ferdigstill(journalpostId: String) {85 val (_, _, result) =86 retryFuel {87 url.plus("/rest/journalpostapi/v1/journalpost/$journalpostId/ferdigstill")88 .httpPatch()89 .authentication()90 .bearer(oidcClient.oidcToken().access_token)91 .jsonBody("""{"journalfoerendeEnhet": "9999"}""")92 .response()93 }94 when (result) {95 is Result.Success -> return96 is Result.Failure -> {97 if (sjekkTilstand(result, journalpostId)) return98 logger.error(99 "Feilet ferdigstilling av journalpost: : $journalpostId, respons fra journalpostapi ${result.error.response}",100 result.error.exception101 )102 throw AdapterException(result.error.exception)103 }104 }105 }106 private fun sjekkTilstand(107 result: Result.Failure<FuelError>,108 journalpostId: String109 ): Boolean {110 val body = result.error.response.data.toString(Charsets.UTF_8)111 val match = feilmeldingRegex.find(body)?.groups?.last()112 val matches = whitelistFeilmeldinger.count {113 match?.value?.contains(it) ?: false114 }115 if (matches >= 1) {116 logger.warn { "Journalpost $journalpostId i en tilstand som er ok. Tilstand: ${match?.value}" }117 return true118 }119 return false120 }121}...

Full Screen

Full Screen

ClientHttpAdapter.kt

Source:ClientHttpAdapter.kt Github

copy

Full Screen

1package com.example.localstore.adapter2import android.util.Log3import com.beust.klaxon.Klaxon4import com.example.localstore.model.Bill5import com.example.localstore.model.Client6import com.example.localstore.model.Product7import com.example.localstore.model.User8import com.github.kittinunf.fuel.core.Parameters9import com.github.kittinunf.fuel.httpGet10import com.github.kittinunf.fuel.httpPatch11import com.github.kittinunf.fuel.httpPost12import com.github.kittinunf.result.Result13class ClientHttpAdapter {14 val url = "http://192.168.0.8:1337"15 fun getClient(id : Int) : Client? {16 Log.i("testingxd","$id")17 var currentUrl = "$url/retrieveClient?id=$id"18 Log.i("testingxd","$currentUrl")19 var client : Client? = null20 currentUrl21 .httpGet()22 .responseString { request, response, result ->23 when(result){24 is Result.Failure -> {25 val ex =result.getException()26 Log.i("httpError", "Error: ${ex.message}")27 }28 is Result.Success -> {29 val data = result.get()30 Log.i("testingxd","$data")31 try {32 var clientAux = Klaxon().parse<Client>(data)33 if (clientAux != null) {34 client = clientAux35 Client.currentClient = client36 Bill.allBills = Client.currentClient!!.bills37 }38 }catch (e : Exception){39 Log.i("testingxd", "Error buscando museos: $e")40 }41 }42 }43 }44 return client45 }46 fun register(bodyClient : Parameters, userName : String, password : String){47 var currentUrl = "$url/Client"48 currentUrl49 .httpPost(bodyClient)50 .responseString{ request, response, result ->51 when(result){52 is Result.Failure -> {53 val ex = result.getException()54 Log.i("httpError", "$ex")55 }56 is Result.Success -> {57 var data = result.get()58 var newClient = Klaxon().parse<Client>(data)59 Client.currentClient = newClient60 var userParameters = listOf(61 "userName" to userName,62 "password" to password,63 "user_person_FK" to newClient?.id64 )65 User.adapter.register(userParameters)66 }67 }68 }69 }70 fun updateClient(body : Parameters, id : Int) {71 var currentUrl = "$url/Client/$id"72 currentUrl73 .httpPatch(body)74 .responseString { request, response, result ->75 when(result){76 is Result.Failure -> {77 var ex = result.getException()78 Log.i("httpError", "$ex")79 }80 is Result.Success -> {81 Log.i("testingxd", "Success")82 }83 }84 }85 }86}...

Full Screen

Full Screen

Fuel.kt

Source:Fuel.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Parameters5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.RequestFactory7import com.github.kittinunf.fuel.core.requests.DownloadRequest8import com.github.kittinunf.fuel.core.requests.UploadRequest9object Fuel : RequestFactory.Convenience by FuelManager.instance {10 var trace = false11 fun trace(function: () -> String) {12 @Suppress("ConstantConditionIf")13 if (trace) println(function())14 }15 fun reset() = FuelManager.instance.reset()16}17fun String.httpGet(parameters: Parameters? = null): Request =18 Fuel.get(this, parameters)19fun RequestFactory.PathStringConvertible.httpGet(parameter: Parameters? = null): Request =20 this.path.httpGet(parameter)21fun String.httpPost(parameters: Parameters? = null): Request =22 Fuel.post(this, parameters)23fun RequestFactory.PathStringConvertible.httpPost(parameters: Parameters? = null): Request =24 this.path.httpPost(parameters)25fun String.httpPut(parameters: Parameters? = null): Request =26 Fuel.put(this, parameters)27fun RequestFactory.PathStringConvertible.httpPut(parameter: Parameters? = null): Request =28 this.path.httpPut(parameter)29fun String.httpPatch(parameters: Parameters? = null): Request =30 Fuel.patch(this, parameters)31fun RequestFactory.PathStringConvertible.httpPatch(parameter: Parameters? = null): Request =32 this.path.httpPatch(parameter)33fun String.httpDelete(parameters: Parameters? = null): Request =34 Fuel.delete(this, parameters)35fun RequestFactory.PathStringConvertible.httpDelete(parameter: Parameters? = null): Request =36 this.path.httpDelete(parameter)37fun String.httpDownload(parameter: Parameters? = null, method: Method = Method.GET): DownloadRequest =38 Fuel.download(this, method, parameter)39fun RequestFactory.PathStringConvertible.httpDownload(parameters: Parameters? = null, method: Method = Method.GET): DownloadRequest =40 this.path.httpDownload(parameters, method)41fun String.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =42 Fuel.upload(this, method, parameters)43fun RequestFactory.PathStringConvertible.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =44 this.path.httpUpload(parameters, method)45fun String.httpHead(parameters: Parameters? = null): Request =46 Fuel.head(this, parameters)47fun RequestFactory.PathStringConvertible.httpHead(parameters: Parameters? = null): Request =48 this.path.httpHead(parameters)...

Full Screen

Full Screen

Firebase.kt

Source:Firebase.kt Github

copy

Full Screen

1package org.vladkanash.repository2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.httpGet5import com.github.kittinunf.fuel.httpPatch6import com.github.kittinunf.fuel.serialization.responseObject7import com.github.kittinunf.result.Result8import com.github.kittinunf.result.Result.Failure9import com.github.kittinunf.result.Result.Success10import com.google.auth.oauth2.GoogleCredentials11import kotlinx.datetime.LocalDate12import kotlinx.serialization.ExperimentalSerializationApi13import kotlinx.serialization.Serializable14import kotlinx.serialization.encodeToString15import kotlinx.serialization.json.Json16private const val ACCESS_TOKEN_PARAM = "access_token"17private const val LAST_MESSAGE_URI = "/lastMessage.json"18@Serializable19data class Message(val text: String? = null, val date: LocalDate)20class Firebase {21 private val credentials: GoogleCredentials22 init {23 FuelManager.instance.basePath = System.getenv("FIREBASE_URL")24 credentials = GoogleCredentials.getApplicationDefault().createScoped(25 listOf(26 "https://www.googleapis.com/auth/userinfo.email",27 "https://www.googleapis.com/auth/firebase.database"28 )29 )30 }31 fun getLastMessage(): Message? {32 val (_, _, result) = LAST_MESSAGE_URI33 .httpGet(listOf(accessTokenParam()))34 .responseObject<Message>()35 return getResponse(result)36 }37 @ExperimentalSerializationApi38 fun updateLastMessage(message: Message): Message? {39 val (_, _, result) = LAST_MESSAGE_URI40 .httpPatch(listOf(accessTokenParam()))41 .body(Json.encodeToString(message))42 .responseObject<Message>()43 return getResponse(result)44 }45 private fun accessTokenParam() = ACCESS_TOKEN_PARAM to46 credentials47 .apply { refreshIfExpired() }48 .accessToken.tokenValue49 private fun getResponse(result: Result<Message, FuelError>) =50 when (result) {51 is Success -> result.get()52 is Failure -> {53 println(result.getException())54 null55 }56 }57}...

Full Screen

Full Screen

WithFuelModifyAndHolder.kt

Source:WithFuelModifyAndHolder.kt Github

copy

Full Screen

1package ru.adavliatov.atomy.toolkit.fuel.service.behaviour2import com.github.kittinunf.fuel.core.extensions.jsonBody3import com.github.kittinunf.fuel.httpPatch4import ru.adavliatov.atomy.common.service.repo.WithEntityToId5import ru.adavliatov.atomy.common.service.repo.WithHolder6import ru.adavliatov.atomy.common.service.repo.WithModifyAndHolder7import ru.adavliatov.atomy.common.type.error.code.ErrorCodes.Unknown8import ru.adavliatov.atomy.common.type.json.WithJsonContext9import ru.adavliatov.atomy.common.ui.api.domain.error.ApiError10import ru.adavliatov.atomy.common.ui.api.header.Headers.AUTHORIZATION11import ru.adavliatov.atomy.toolkit.fuel.service.WithHolderToHeader12import ru.adavliatov.atomy.toolkit.fuel.service.deserialize.WithFuelIdDeserializer13interface WithFuelModifyAndHolder<Holder : WithHolder, Id : Any, View : Any> :14 WithModifyAndHolder<Holder, View>,15 WithJsonContext,16 WithFuelIdDeserializer<Id>,17 WithHolderToHeader<Holder>,18 WithFuelUrl,19 WithEntityToId<Id, View> {20 override fun modify(holder: Holder, item: View): View = "$url/${item.id()}"21 .httpPatch()22 .jsonBody(context.toJson(item).let { context.asString(it) })23 .header(24 AUTHORIZATION to holder.toHeader()25 )26 .response()27 .let { (_, rs, result) ->28 result29 .fold(30 { item },31 {32 throw ApiError(rs.statusCode, Unknown, message = it.localizedMessage)33 }34 )35 }36}...

Full Screen

Full Screen

AtualizarSenhaService.kt

Source:AtualizarSenhaService.kt Github

copy

Full Screen

1package br.com.martinsgms.relatorioacessivel.service2import android.util.Log3import br.com.martinsgms.relatorioacessivel.config.HttpConfig4import br.com.martinsgms.relatorioacessivel.model.UsuarioModel5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.core.Method7import com.github.kittinunf.fuel.coroutines.awaitStringResponse8import com.github.kittinunf.fuel.httpPatch9import com.google.gson.Gson10class AtualizarSenhaService {11 var gson = Gson()12 init {13 HttpConfig.config()14 }15 suspend fun atualizaSenha(usuarioModel: UsuarioModel, token : String): String {16 Log.d("toks", "too->> $token")17 Log.d("json", "too->> ${gson.toJson(usuarioModel)}")18 val (request, response, result) = Fuel.request(Method.PUT, "/usuario/senha")19 .header("Content-Type" to "application/json", "Authorization" to "Bearer $token")20 .body(gson.toJson(usuarioModel))21 .awaitStringResponse()22 return result23 }24}...

Full Screen

Full Screen

String.httpPatch

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.requests.CancellableRequest6import com.github.kittinunf.fuel.core.requests.DefaultBody7import com.github.kittinunf.fuel.core.requests.DefaultRequest8import com.github.kittinunf.fuel.core.requests.DefaultRequestTask9import com.github.kittinunf.fuel.core.requests.TaskCompletionSource10import com.github.kittinunf.fuel.core.requests.cUrlString11import com.github.kittinunf.fuel.core.requests.cUrlStringRequest12import com.github.kittinunf.fuel.core.requests.download13import com.github.kittinunf.fuel.core.requests.httpBody14import com.github.kittinunf.fuel.core.requests.httpHeaders15import com.github.kittinunf.fuel.core.requests.httpMethod16import com.github.kittinunf.fuel.core.requests.httpParameters17import com.github.kittinunf.fuel.core.requests.httpUrl18import com.github.kittinunf.fuel.core.requests.progress19import com.github.kittinunf.fuel.core.requests.response20import com.github.kittinunf.fuel.core.requests.responseString21import com.github.kittinunf.fuel.core.requests.task22import com.github.kittinunf.fuel.core.requests.uploadProgress23import com.github.kittinunf.fuel.core.requests.url24import com.github.kittinunf.fuel.core.requests.validate25import com.github.kittinunf.fuel.core.requests.validateResponse26import com.github.kittinunf.fuel.core.requests.validateResponseToResult27import com.github.kittinunf.fuel.core.requests.validateToResult28import com.github.kittinunf.fuel.core.requests.write29import com.github.kittinunf.fuel.core.requests.writeResponse30import com.github.kittinunf.fuel.core.requests.writeResponseToResult31import com.github.kittinunf.fuel.core.requests.writeToResult32import com.github.kittinunf.fuel.core.requests.writer33import com.github.kittinunf.fuel.core.requests.writerResponse34import com.github.kitt

Full Screen

Full Screen

String.httpPatch

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.extensions.authentication4import com.github.kittinunf.fuel.core.extensions.cUrlString5import com.github.kittinunf.fuel.core.extensions.jsonBody6import com.github.kittinunf.fuel.core.extensions.responseString7import com.github.kittinunf.fuel.core.requests.CancellableRequest8import com.github.kittinunf.fuel.core.requests.DefaultBody9import com.github.kittinunf.fuel.core.requests.Request10import com.github.kittinunf.fuel.core.requests.cUrlRequest11import com.github.kittinunf.fuel.core.requests.cUrlRequestString12import com.github.kittinunf.fuel.core.requests.cUrlString13import com.github.kittinunf.fuel.core.requests.jsonBody14import com.github.kittinunf.fuel.core.requests.responseString15import com.github.kittinunf.fuel.core.requests.streamResponse16import com.github.kittinunf.fuel.core.requests.taskCompletionSource17import com.github.kittinunf.fuel.core.requests.taskCompletionSourceResponse18import com.github.kittinunf.fuel.core.requests.taskCompletionSourceResponseString19import com.github.kittinunf.fuel.core.requests.taskCompletionSourceString20import com.github.kittinunf.fuel.core.requests.validateResponse21import com.github.kittinunf.fuel.core.requests.validateResponseString22import com.github.kittinunf.fuel.core.requests.validateResponseStringResult23import com.github.kittinunf.fuel.core.requests.validateResponseStringResultCurl24import com.github.kittinunf.fuel.core.requests.validateResponseStringResultCurlString25import com.github.kittinunf.fuel.core.requests.validateResponseStringResultString26import com.github.kittinunf.fuel.core.requests.validateResponseStringResultStringCurl27import com.github.kittinunf.fuel.core.requests.validateResponseStringResultStringCurlString28import com.github.kittinunf.fuel.core.requests.validateResponseStringResultStringResponse29import com.github.kittinunf.fuel.core.requests.validateResponseStringResultStringResponseCurl30import com.github.kittinunf.fuel.core.requests.validateResponseStringResultString

Full Screen

Full Screen

String.httpPatch

Using AI Code Generation

copy

Full Screen

1package com.zetcode;2import com.github.kittinunf.fuel.Fuel;3public class FuelPatchEx {4 public static void main(String[] args) {5 String response = Fuel.patch(url).responseString().get().second;6 System.out.println(response);7 }8}9{10 "args": {}, 11 "files": {}, 12 "form": {}, 13 "headers": {14 },

Full Screen

Full Screen

String.httpPatch

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.Fuel2result.fold({ d -> println(d) }, { err -> println(err) })3import com.github.kittinunf.fuel.Fuel4result.fold({ d -> println(d) }, { err -> println(err) })5import com.github.kittinunf.fuel.Fuel6result.fold({ d -> println(d) }, { err -> println(err) })7import com.github.kittinunf.fuel.Fuel8result.fold({ d -> println(d) }, { err -> println(err) })9import com.github.kittinunf.fuel.Fuel10result.fold({ d -> println(d) }, { err -> println(err) })11import com.github.kittinunf.fuel.Fuel12result.fold({ d -> println(d) }, { err -> println(err) })13import com.github.kittinunf.fuel.Fuel14result.fold({ d -> println(d) }, { err -> println(err) })

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