How to use randomUuid method of com.github.kittinunf.fuel.coroutines.private class

Best Fuel code snippet using com.github.kittinunf.fuel.coroutines.private.randomUuid

MainActivity.kt

Source:MainActivity.kt Github

copy

Full Screen

1package com.example.findmyrep2import android.Manifest3import android.content.Context4import android.content.pm.PackageManager5import android.os.Bundle6import android.util.Log7import androidx.appcompat.app.AppCompatActivity8import androidx.core.app.ActivityCompat9import androidx.core.content.ContextCompat10import com.example.findmyrep.models.voicify.*11import com.github.kittinunf.fuel.Fuel12import com.github.kittinunf.fuel.gson.jsonBody13import com.github.kittinunf.fuel.gson.responseObject14import com.google.android.material.snackbar.Snackbar15import com.squareup.picasso.OkHttp3Downloader16import com.squareup.picasso.Picasso17import io.spokestack.spokestack.OnSpeechEventListener18import io.spokestack.spokestack.SpeechContext19import io.spokestack.spokestack.SpeechPipeline20import io.spokestack.spokestack.nlu.NLUResult21import io.spokestack.spokestack.nlu.TraceListener22import io.spokestack.spokestack.nlu.tensorflow.TensorflowNLU23import io.spokestack.spokestack.tts.SynthesisRequest24import io.spokestack.spokestack.tts.TTSManager25import io.spokestack.spokestack.util.EventTracer26import kotlinx.android.synthetic.main.activity_main.*27import kotlinx.android.synthetic.main.content_main.*28import kotlinx.coroutines.Dispatchers29import kotlinx.coroutines.GlobalScope30import kotlinx.coroutines.launch31import kotlinx.coroutines.withContext32import okhttp3.OkHttpClient33import okhttp3.Protocol34import java.io.File35import java.io.FileOutputStream36import java.io.IOException37import java.io.InputStream38import java.util.*39class MainActivity : AppCompatActivity(), OnSpeechEventListener, TraceListener {40 private var pipeline: SpeechPipeline? = null41 private var tts: TTSManager? = null42 private var voicifyUser: VoicifyUser? = null43 private var sessionId: String? = null44 private var client: OkHttpClient? = null45 private var picasso: Picasso? = null46 override fun onCreate(savedInstanceState: Bundle?) {47 super.onCreate(savedInstanceState)48 setContentView(R.layout.activity_main)49 setSupportActionBar(toolbar)50 sessionId = UUID.randomUUID().toString()51 checkForModels()52 voicifyUser = VoicifyUser(UUID.randomUUID().toString(), UUID.randomUUID().toString())53 client = OkHttpClient.Builder()54 .protocols(Collections.singletonList(Protocol.HTTP_1_1))55 .build()56 picasso = Picasso.Builder(this)57 .downloader(OkHttp3Downloader(client))58 .build()59 Picasso.setSingletonInstance(picasso!!)60 pipeline = SpeechPipeline.Builder()61 .useProfile("io.spokestack.spokestack.profile.VADTriggerAndroidASR")62 .setAndroidContext(applicationContext)63 .addOnSpeechEventListener(this)64 .build()65 tts = TTSManager.Builder()66 .setTTSServiceClass("io.spokestack.spokestack.tts.SpokestackTTSService")67 .setOutputClass("io.spokestack.spokestack.tts.SpokestackTTSOutput")68 .setProperty("spokestack-id", "3b40def8-f77e-42f8-8d5c-47a8fd7e4797")69 .setProperty(70 "spokestack-secret",71 "9DAC2C5AA917752AB1854B47DE1990560203394AF5716E157EDD57C7DAD99949"72 )73 .setAndroidContext(applicationContext)74 .setLifecycle(lifecycle)75 .build()76 fab.setOnClickListener { view ->77 tts?.stopPlayback()78 when {79 ContextCompat.checkSelfPermission(80 this,81 Manifest.permission.RECORD_AUDIO82 ) == PackageManager.PERMISSION_GRANTED -> {83 // You can use the API that requires the permission.84 if (pipeline?.isRunning == true) {85 pipeline?.stop()86 Snackbar.make(view, "No longer listening", Snackbar.LENGTH_LONG)87 .setAction("Action", null).show()88 } else {89 pipeline?.start()90 Snackbar.make(view, "Now listening", Snackbar.LENGTH_LONG)91 .setAction("Action", null).show()92 }93 }94 else -> {95 // You can directly ask for the permission96 ActivityCompat97 .requestPermissions(98 this,99 Array<String>(1) { _ -> Manifest.permission.RECORD_AUDIO },100 1101 );102 }103 }104 }105 }106 override fun onRequestPermissionsResult(107 requestCode: Int,108 permissions: Array<out String>,109 grantResults: IntArray110 ) {111 super.onRequestPermissionsResult(requestCode, permissions, grantResults)112 }113 override fun onEvent(event: SpeechContext.Event?, context: SpeechContext?) {114 when (event) {115 SpeechContext.Event.ACTIVATE -> println("ACTIVATED")116 SpeechContext.Event.DEACTIVATE -> println("DEACTIVATED")117 SpeechContext.Event.RECOGNIZE -> context?.let { handleSpeech(it.transcript) }118 SpeechContext.Event.TIMEOUT -> println("TIMEOUT")119 SpeechContext.Event.ERROR -> context?.let { println("ERROR: ${it.error}") }120 else -> {121 // do nothing122 }123 }124 }125 private fun handleSpeech(transcript: String) {126 pipeline?.stop()127 val nlu = TensorflowNLU.Builder()128 .setProperty("nlu-model-path", "$cacheDir/nlu.tflite")129 .setProperty("nlu-metadata-path", "$cacheDir/metadata.json")130 .setProperty("wordpiece-vocab-path", "$cacheDir/vocab.txt")131 .addTraceListener(this)132 .build()133 GlobalScope.launch(Dispatchers.Default) {134 nlu?.let {135 val result = it.classify(transcript).get()136 withContext(Dispatchers.Main) {137 Snackbar.make(fab, result.intent, Snackbar.LENGTH_LONG)138 .setAction("Action", null).show()139 val requestModel = getVoicifyRequest(transcript, result)140 Fuel.post("https://assistant.voicify.com/api/customAssistant/handlerequest?applicationId=9bf40a95-46df-41f5-8eb7-ebeae97f61d5&applicationSecret=NjU1Zjg1N2MtNjljZi00ZmU5LTllMDctMzI4NmI5ZjQ3NDE4\n")141 .jsonBody(requestModel!!)142 .responseObject<VoicifyCustomAssistantResponse> { _, _, voicifyResult ->143 // handle result similarly as it is shown by the core module144 Log.i("VOICIFY_RESPONSE", voicifyResult.component1()?.ssml)145 displayText.text = voicifyResult.component1()?.displayText;146 if (voicifyResult.component1()?.foregroundImage != null) {147 Picasso.get().load(voicifyResult.component1()?.foregroundImage?.url)148 .into(displayImage);149 }150 val ttsRequest =151 SynthesisRequest.Builder(voicifyResult.component1()?.ssml)152 .withMode(SynthesisRequest.Mode.SSML).build()153// val ttsRequest = SynthesisRequest.Builder("Here's what I found. Elizabeth Warren, and you can call them at a phone number. Would you like to learn about your governor?").build()154 tts?.synthesize(ttsRequest)155 }156 }157 }158 }159 }160 private fun getVoicifyRequest(161 transcript: String,162 result: NLUResult163 ): VoicifyCustomAssistantRequest? {164 var requestModel: VoicifyCustomAssistantRequest? = null;165 val requestContext: VoicifyRequestContext = VoicifyRequestContext(166 sessionId!!,167 false,168 "IntentRequest",169 null,170 transcript,171 "Android App",172 true,173 "en-US",174 null175 )176 if (result.intent == "SenatorZipCodeIntent" || result.intent == "MayorZipCodeIntent" || result.intent == "GovZipCodeIntent" || result.intent == "AllZipCodeIntent") {177 requestContext.requestName = result.intent178 requestContext.slots = result.slots.mapValues { it.value.rawValue.toString() }179 requestContext.requiresLanguageUnderstanding = false180 }181 requestModel = VoicifyCustomAssistantRequest(182 UUID.randomUUID().toString(),183 requestContext,184 VoicifyDevice(185 UUID.randomUUID().toString(),186 "Android Phone",187 true,188 true,189 true,190 true,191 true,192 true,193 true,194 true195 ),196 voicifyUser!!197 );198 return requestModel199 }200 private fun checkForModels() {201 // PREF_NAME and VERSION_KEY are static Strings set at the top of the file;202 // we want PREF_NAME to uniquely refer to our app, and VERSION_KEY to be203 // unique within the app itself204 if (!modelsCached()) {205 decompressModels()206 } else {207 val currentVersionCode = BuildConfig.VERSION_CODE208 val prefs = getSharedPreferences("com.suavepirate.findmyrep", Context.MODE_PRIVATE)209 val savedVersionCode = prefs.getInt("VERSION_KEY", -1)210 if (currentVersionCode != savedVersionCode) {211 decompressModels()212 // Update the shared preferences with the current version code213 prefs.edit().putInt("VERSION_KEY", currentVersionCode).apply()214 }215 }216 }217 private fun modelsCached(): Boolean {218 val nluName = "nlu.tflite"219 val nluFile = File("$cacheDir/$nluName")220 return nluFile.exists()221 }222 private fun decompressModels() {223 try {224 cacheAsset("nlu.tflite")225 cacheAsset("metadata.json")226 cacheAsset("vocab.txt")227 cacheAsset("minecraft-recipe.json")228 } catch (e: IOException) {229 Log.e("FINDMYREP", "Unable to cache NLU data", e)230 }231 }232 @Throws(IOException::class)233 private fun cacheAsset(assetName: String) {234 val assetFile = File("$cacheDir/$assetName")235 val inputStream: InputStream = assets.open(assetName)236 val size: Int = inputStream.available()237 val buffer = ByteArray(size)238 inputStream.read(buffer)239 inputStream.close()240 val fos = FileOutputStream(assetFile)241 fos.write(buffer)242 fos.close()243 }244 override fun onTrace(level: EventTracer.Level?, message: String?) {245 Log.w("FINDMYREP", message);246 }247}...

Full Screen

Full Screen

ObjectTest.kt

Source:ObjectTest.kt Github

copy

Full Screen

...32 response = mock.response().withStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED).withHeader("foo", "bar").withBody("error:unauthorized")33 )34 return Fuel.request(method, mock.path(path))35 }36 private fun randomUuid(path: String = "uuid"): Request {37 mock.chain(38 request = mock.request().withPath("/$path"),39 response = mock.response().withBody(UUID.randomUUID().toString())40 )41 return Fuel.request(Method.GET, mock.path(path))42 }43 @Test44 fun awaitObject() = runBlocking {45 try {46 val data = randomUuid().awaitObject(UUIDResponseDeserializer)47 assertThat(data, notNullValue())48 } catch (exception: Exception) {49 fail("Expected pass, actual error $exception")50 }51 }52 @Test(expected = FuelError::class)53 fun awaitObjectThrows() = runBlocking {54 val data = mocked401().awaitObject(UUIDResponseDeserializer)55 fail("Expected error, actual data $data")56 }57 @Test58 fun awaitObjectResponse() = runBlocking {59 try {60 val (request, response, data) = randomUuid().awaitObjectResponse(UUIDResponseDeserializer)61 assertThat(request, notNullValue())62 assertThat(response, notNullValue())63 assertThat(data, notNullValue())64 } catch (exception: Exception) {65 fail("Expected pass, actual error $exception")66 }67 }68 @Test(expected = FuelError::class)69 fun awaitObjectResponseThrows() = runBlocking {70 val (_, _, data) = mocked401().awaitObjectResponse(UUIDResponseDeserializer)71 fail("Expected error, actual data $data")72 }73 @Test74 fun awaitObjectResult() = runBlocking {75 val (data, error) = randomUuid().awaitObjectResult(UUIDResponseDeserializer)76 assertThat(data, notNullValue())77 }78 @Test79 fun awaitObjectResultFailure() = runBlocking {80 val (data, error) = mocked401().awaitObjectResult(UUIDResponseDeserializer)81 assertThat(error, notNullValue())82 }83 @Test84 fun awaitObjectResponseResult() = runBlocking {85 val (request, response, result) = randomUuid().awaitObjectResponseResult(UUIDResponseDeserializer)86 val (data, error) = result87 assertThat(data, notNullValue())88 assertThat(request, notNullValue())89 assertThat(response, notNullValue())90 }91 @Test92 fun awaitObjectResponseResultFailure() = runBlocking {93 val (data, response, result) = mocked401().awaitObjectResponseResult(UUIDResponseDeserializer)94 assertThat(data, notNullValue())95 assertThat(response, notNullValue())96 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_UNAUTHORIZED))97 assertThat(response.isSuccessful, equalTo(false))98 assertThat(response.headers["foo"], equalTo(listOf("bar") as Collection<String>))99 val (_, error) = result100 assertThat(error!!.response, equalTo(response))101 assertThat(error.response.statusCode, equalTo(response.statusCode))102 assertThat(error.response.body(), equalTo(response.body()))103 }104 @Test105 fun awaitUnit() = runBlocking {106 runCatching {107 val data = randomUuid().awaitUnit()108 assertThat(data, notNullValue())109 assertThat(data, equalTo(Unit))110 }.getOrElse {111 fail("Expected pass, actual error $it")112 }113 }114 @Test115 fun captureDeserializationException() = runBlocking {116 val (request, response, result) = reflectedRequest(Method.GET, "reflected")117 .awaitObjectResponseResult(object : ResponseDeserializable<Unit> {118 override fun deserialize(content: String): Unit? {119 throw IllegalStateException("some deserialization exception")120 }121 })...

Full Screen

Full Screen

OppgaveClientV2.kt

Source:OppgaveClientV2.kt Github

copy

Full Screen

1package no.nav.hjelpemidler.oppgave.oppgave2import com.fasterxml.jackson.databind.JsonNode3import com.fasterxml.jackson.databind.ObjectMapper4import com.github.kittinunf.fuel.core.ResponseDeserializable5import com.github.kittinunf.fuel.core.extensions.jsonBody6import com.github.kittinunf.fuel.coroutines.awaitObject7import com.github.kittinunf.fuel.httpPost8import kotlinx.coroutines.Dispatchers9import kotlinx.coroutines.withContext10import mu.KotlinLogging11import no.nav.hjelpemidler.oppgave.AzureClient12import no.nav.hjelpemidler.oppgave.oppgave.model.OpprettBehandleSakOppgaveRequest13import java.time.LocalDate14import java.util.UUID15private val logger = KotlinLogging.logger {}16class OppgaveClientV2(17 private val baseUrl: String,18 private val accesstokenScope: String,19 private val azureClient: AzureClient20) {21 companion object {22 private val objectMapper = ObjectMapper()23 const val BEHANDLINGSTYPE = "ae0227" // Digital søknad24 const val OPPGAVETYPE_BEH_SAK = "BEH_SAK"25 const val OPPGAVE_PRIORITET_NORM = "NORM"26 const val TEMA = "HJE"27 const val TEMA_GRUPPE = "HJLPM"28 const val BESKRIVELSE_OPPGAVE = "Digital søknad om hjelpemidler"29 }30 suspend fun opprettBehandleSakOppgave(aktorId: String, journalpostId: String, enhet: String, dokumentBeskrivelse: String): String {31 logger.info { "Oppretter oppgave for ferdigstilt journalpost" }32 val requestBody = OpprettBehandleSakOppgaveRequest(33 aktorId, journalpostId, dokumentBeskrivelse,34 TEMA_GRUPPE, TEMA, OPPGAVETYPE_BEH_SAK, BEHANDLINGSTYPE,35 hentAktivDato(), hentFristFerdigstillelse(), OPPGAVE_PRIORITET_NORM, enhet36 )37 val jsonBody = objectMapper.writeValueAsString(requestBody)38 return withContext(Dispatchers.IO) {39 kotlin.runCatching {40 val correlationID = UUID.randomUUID().toString()41 logger.info("DEBUG: akriverSøknad correlationID=$correlationID")42 baseUrl.httpPost()43 .header("Content-Type", "application/json")44 .header("Accept", "application/json")45 .header("Authorization", "Bearer ${azureClient.getToken(accesstokenScope).accessToken}")46 .header("X-Correlation-ID", correlationID)47 .jsonBody(jsonBody)48 .awaitObject(49 object : ResponseDeserializable<JsonNode> {50 override fun deserialize(content: String): JsonNode {51 return ObjectMapper().readTree(content)52 }53 }54 )55 .let {56 when (it.has("id")) {57 true -> it["id"].toString()58 false -> throw OppgaveException("Klarte ikke å opprette oppgave")59 }60 }61 }62 .onFailure {63 logger.error { it.message }64 }65 }66 .getOrThrow()67 }68 private fun hentFristFerdigstillelse() =69 LocalDate.now().toString()70 private fun hentAktivDato() =71 LocalDate.now().toString()72}73internal class OppgaveExceptionV2(msg: String) : RuntimeException(msg)...

Full Screen

Full Screen

PdlClient.kt

Source:PdlClient.kt Github

copy

Full Screen

1package no.nav.hjelpemidler.soknad.mottak.client2import com.fasterxml.jackson.databind.JsonNode3import com.fasterxml.jackson.databind.ObjectMapper4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.ResponseDeserializable6import com.github.kittinunf.fuel.core.extensions.jsonBody7import com.github.kittinunf.fuel.coroutines.awaitObject8import com.github.kittinunf.fuel.httpPost9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.withContext11import mu.KotlinLogging12import no.nav.hjelpemidler.soknad.mottak.JacksonMapper13import no.nav.hjelpemidler.soknad.mottak.aad.AzureClient14import java.util.UUID15private val logger = KotlinLogging.logger {}16internal class PdlClient(17 private val azureClient: AzureClient,18 private val baseUrl: String,19 private val accesstokenScope: String,20) {21 suspend fun hentKommunenr(fnrBruker: String): String? {22 val body = KommunenrQuery(query = hentKommunenrQuery, variables = mapOf("ident" to fnrBruker))23 val jsonNode = withContext(Dispatchers.IO) {24 kotlin.runCatching {25 baseUrl.httpPost()26 .headers()27 .jsonBody(JacksonMapper.objectMapper.writeValueAsString(body))28 .awaitObject(29 object : ResponseDeserializable<JsonNode> {30 override fun deserialize(content: String): JsonNode {31 return ObjectMapper().readTree(content)32 }33 }34 )35 }36 .onSuccess {37 if (it.has("errors")) {38 throw RuntimeException("Feil ved henting av personinformasjon fra PDL ${it.get("errors")}")39 }40 }41 .onFailure {42 logger.error("Feil ved kall til PDL ${it.message}", it)43 throw it44 }45 .getOrThrow()46 }47 return jsonNode["data"].get("hentPerson")?.get("bostedsadresse")?.firstOrNull()?.get("vegadresse")48 ?.get("kommunenummer")?.textValue()49 }50 private fun Request.headers() = this.header(51 mapOf(52 "Content-Type" to "application/json",53 "Accept" to "application/json",54 "Tema" to "HJE",55 "Authorization" to "Bearer ${azureClient.getToken(accesstokenScope).accessToken}",56 "X-Correlation-ID" to UUID.randomUUID().toString()57 )58 )59}60internal data class KommunenrQuery(val query: String, val variables: Map<String, String>)61private val hentKommunenrQuery =62 """63 query(${'$'}ident: ID!) {64 hentPerson(ident: ${'$'}ident) {65 bostedsadresse(historikk: false ) {66 vegadresse {67 kommunenummer68 }69 }70 }71 }72 """.trimIndent()...

Full Screen

Full Screen

InfotrygdProxyClient.kt

Source:InfotrygdProxyClient.kt Github

copy

Full Screen

1package no.nav.hjelpemidler.soknad.mottak.client2import com.fasterxml.jackson.module.kotlin.readValue3import com.github.kittinunf.fuel.core.Request4import com.github.kittinunf.fuel.core.ResponseDeserializable5import com.github.kittinunf.fuel.core.extensions.jsonBody6import com.github.kittinunf.fuel.coroutines.awaitObject7import com.github.kittinunf.fuel.httpPost8import kotlinx.coroutines.Dispatchers9import kotlinx.coroutines.withContext10import mu.KotlinLogging11import no.nav.hjelpemidler.soknad.mottak.JacksonMapper12import no.nav.hjelpemidler.soknad.mottak.aad.AzureClient13import java.time.LocalDate14import java.util.UUID15private val logger = KotlinLogging.logger {}16internal interface InfotrygdProxyClient {17 suspend fun harVedtakFor(fnr: String, saksblokk: String, saksnr: String, vedtaksDato: LocalDate): Boolean18}19internal class InfotrygdProxyClientImpl(20 private val baseUrl: String,21 private val azureClient: AzureClient,22 private val accesstokenScope: String,23) : InfotrygdProxyClient {24 override suspend fun harVedtakFor(fnr: String, saksblokk: String, saksnr: String, vedtaksDato: LocalDate): Boolean {25 data class Request(26 val fnr: String,27 val saksblokk: String,28 val saksnr: String,29 val vedtaksDato: LocalDate,30 )31 data class Response(32 val resultat: Boolean,33 )34 return withContext(Dispatchers.IO) {35 kotlin.runCatching {36 "$baseUrl/har-vedtak-for".httpPost()37 .headers()38 .jsonBody(39 JacksonMapper.objectMapper.writeValueAsString(40 Request(41 fnr,42 saksblokk,43 saksnr,44 vedtaksDato,45 )46 )47 )48 .awaitObject(49 object : ResponseDeserializable<Response> {50 override fun deserialize(content: String): Response {51 return JacksonMapper.objectMapper.readValue(content)52 }53 }54 ).resultat55 }.onFailure {56 logger.error { it.message }57 }.getOrDefault(false)58 }59 }60 private fun Request.headers() = this.header(61 mapOf(62 "Content-Type" to "application/json",63 "Accept" to "application/json",64 "Authorization" to "Bearer ${azureClient.getToken(accesstokenScope).accessToken}",65 "X-Correlation-ID" to UUID.randomUUID().toString()66 )67 )68}...

Full Screen

Full Screen

StressTest.kt

Source:StressTest.kt Github

copy

Full Screen

1package net.wussmann.rds.serverless2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.awaitResponse4import com.github.kittinunf.fuel.coroutines.awaitStringResponse5import kotlinx.coroutines.Job6import kotlinx.coroutines.async7import kotlinx.coroutines.delay8import kotlinx.coroutines.joinAll9import kotlinx.coroutines.launch10import kotlinx.coroutines.runBlocking11import java.lang.Exception12import java.util.UUID13import kotlin.random.Random14import kotlin.time.measureTimedValue15private val fuel = FuelManager().apply {16 basePath = "<URL GOES HERE>"17}18private val connectionType = CloudWatchService.ConnectionType.DATA19private val slowMode = true // connectionType == CloudWatchService.ConnectionType.JDBC20private val maxRequests = 100_00021private var requests = 022/**23 * Stress test to run multiple read & write operations at the same time24 */25fun main() {26 runBlocking {27 while (true) {28 if (requests >= maxRequests) break29 launch {30 if (Random.nextBoolean()) {31 readOperation()32 } else {33 writeOperation()34 }35 }36 if (slowMode) {37 delay(10)38 }39 requests++40 println("Requests $requests")41 }42 }43}44private suspend fun readOperation() {45 measureTimedValue {46 try {47 fuel.get("/users")48 .header("DB-Connection", connectionType.name)49 .awaitStringResponse()50 } catch (e: Exception) {51 println("Error ${e.message}")52 null53 }54 }.let { (res, duration) ->55 println("Read: $duration, ${res?.second?.header("Connection-Type")?.firstOrNull()}, ${res?.second?.body()?.asString("application/json")?.substring(0..7)}...")56 }57}58private suspend fun writeOperation() {59 measureTimedValue {60 try {61 fuel.post("/users")62 .header("DB-Connection", connectionType.name)63 .body(64 """65 {"username": "${UUID.randomUUID().toString().substring(0, 6)}"}66 """.trimIndent()67 )68 .awaitStringResponse()69 } catch (e: Exception) {70 println("Error ${e.message}")71 null72 }73 }.let { (res, duration) ->74 println("Write: $duration, ${res?.second?.header("Connection-Type")?.firstOrNull()}, ${res?.second?.body()?.asString("application/json")?.substring(0..7)}...")75 }76}...

Full Screen

Full Screen

ConsentsHelper.kt

Source:ConsentsHelper.kt Github

copy

Full Screen

1package com.dproductions.sob.helpers2import com.dproductions.sob.exceptions.ConsentsException3import com.dproductions.sob.structures.banks.SwedbankBic4import com.dproductions.sob.structures.consents.Consent5import com.dproductions.sob.structures.consents.CreateConsentRequest6import com.dproductions.sob.structures.credentials.OauthCredentials7import com.github.kittinunf.fuel.core.FuelError8import com.github.kittinunf.fuel.core.HttpException9import com.github.kittinunf.fuel.coroutines.awaitObject10import com.github.kittinunf.fuel.httpPost11import com.google.gson.Gson12import io.mikael.urlbuilder.UrlBuilder13import java.util.*14class ConsentsHelper(private val oauthCredentials: OauthCredentials, private val bic: SwedbankBic, isProduction: Boolean) : ApiHelper(isProduction) {15 override val endpoint = getConsentsHelperEndpoint()16 suspend fun createConsent(createConsentRequest: CreateConsentRequest): Consent {17 val url = UrlBuilder18 .fromString(endpoint)19 .addParameter("bic", bic.value)20 val consent: Consent21 try {22 consent = url.toString()23 .httpPost()24 .body(Gson().toJson(createConsentRequest))25 .header("Content-Type", "application/json")26 .header("Authorization", "Bearer ${oauthCredentials.accessToken}")27 .header("X-Request-ID", UUID.randomUUID().toString())28 .header("Date", Date().toString())29 .awaitObject(Consent.Deserializer())30 } catch (exception: Exception) {31 when (exception){32 is HttpException -> throw ConsentsException(exception.message)33 is FuelError -> throw ConsentsException(exception.message)34 else -> throw ConsentsException("Generic exception received with message: ${exception.message}")35 }36 }37 return consent38 }39}...

Full Screen

Full Screen

OppslagClient.kt

Source:OppslagClient.kt Github

copy

Full Screen

1package no.nav.hjelpemidler.soknad.mottak.metrics.kommune2import com.fasterxml.jackson.module.kotlin.readValue3import com.github.kittinunf.fuel.core.ResponseDeserializable4import com.github.kittinunf.fuel.coroutines.awaitObjectResponse5import com.github.kittinunf.fuel.httpGet6import no.nav.hjelpemidler.soknad.mottak.Configuration7import no.nav.hjelpemidler.soknad.mottak.JacksonMapper8import org.slf4j.LoggerFactory9import java.util.UUID10class OppslagClient(11 private val oppslagUrl: String = Configuration.oppslagUrl12) {13 suspend fun hentAlleKommuner(): Map<String, KommuneDto> {14 val kommunenrUrl = "$oppslagUrl/geografi/kommunenr"15 LOG.info("Henter alle kommuner fra $kommunenrUrl")16 try {17 return kommunenrUrl.httpGet()18 .header(19 mapOf(20 "Accept" to "application/json",21 "X-Correlation-ID" to UUID.randomUUID().toString()22 )23 )24 .awaitObjectResponse(25 object : ResponseDeserializable<Map<String, KommuneDto>> {26 override fun deserialize(content: String): Map<String, KommuneDto> {27 return JacksonMapper.objectMapper.readValue(content)28 }29 }30 ).third31 } catch (e: Exception) {32 LOG.error("Henting av kommune feilet", e)33 throw e34 }35 }36 companion object {37 private val LOG = LoggerFactory.getLogger(OppslagClient::class.java)38 }39}...

Full Screen

Full Screen

randomUuid

Using AI Code Generation

copy

Full Screen

1private val randomUuid = RandomUuid()2private val randomUuid = RandomUuid()3private val randomUuid = RandomUuid()4private val randomUuid = RandomUuid()5private val randomUuid = RandomUuid()6private val randomUuid = RandomUuid()7private val randomUuid = RandomUuid()8private val randomUuid = RandomUuid()9private val randomUuid = RandomUuid()10private val randomUuid = RandomUuid()11private val randomUuid = RandomUuid()12private val randomUuid = RandomUuid()13private val randomUuid = RandomUuid()14private val randomUuid = RandomUuid()15private val randomUuid = RandomUuid()16private val randomUuid = RandomUuid()17private val randomUuid = RandomUuid()18private val randomUuid = RandomUuid()19private val randomUuid = RandomUuid()20private val randomUuid = RandomUuid()21private val randomUuid = RandomUuid()22private val randomUuid = RandomUuid()23private val randomUuid = RandomUuid()24private val randomUuid = RandomUuid()25private val randomUuid = RandomUuid()26private val randomUuid = RandomUuid()

Full Screen

Full Screen

randomUuid

Using AI Code Generation

copy

Full Screen

1private val randomUuid = RandomUuid()2private fun randomUuid() = randomUuid.randomUuid()3private val randomUuid = RandomUuid()4private fun randomUuid() = randomUuid.randomUuid()5private val randomUuid = RandomUuid()6private fun randomUuid() = randomUuid.randomUuid()7private val randomUuid = RandomUuid()8private fun randomUuid() = randomUuid.randomUuid()9private val randomUuid = RandomUuid()10private fun randomUuid() = randomUuid.randomUuid()11private val randomUuid = RandomUuid()12private fun randomUuid() = randomUuid.randomUuid()13private val randomUuid = RandomUuid()14private fun randomUuid() = randomUuid.randomUuid()15private val randomUuid = RandomUuid()16private fun randomUuid() = randomUuid.randomUuid()17private val randomUuid = RandomUuid()18private fun randomUuid() = randomUuid.randomUuid()19private val randomUuid = RandomUuid()20private fun randomUuid() = randomUuid.randomUuid()21private val randomUuid = RandomUuid()22private fun randomUuid() = randomUuid.randomUuid()23private val randomUuid = RandomUuid()24private fun randomUuid() = randomUuid.randomUuid()25private val randomUuid = RandomUuid()26private fun randomUuid() = randomUuid.randomUuid()

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