Best Fuel code snippet using com.github.kittinunf.fuel.jackson.ObjectBody.Request.objectBody
VideoActivity.kt
Source:VideoActivity.kt
1package org.ar.ar_android_video_base2import android.os.Bundle3import android.view.KeyEvent4import android.view.View5import android.widget.Toast6import androidx.appcompat.app.AppCompatActivity7import androidx.recyclerview.widget.GridLayoutManager8import com.github.kittinunf.fuel.Fuel9import com.github.kittinunf.fuel.core.FuelError10import com.github.kittinunf.fuel.core.Request11import com.github.kittinunf.fuel.core.Response12import com.github.kittinunf.fuel.core.isSuccessful13import com.github.kittinunf.fuel.jackson.objectBody14import com.github.kittinunf.fuel.jackson.responseObject15import com.github.kittinunf.result.Result16import kotlinx.coroutines.CoroutineScope17import kotlinx.coroutines.Dispatchers18import kotlinx.coroutines.coroutineScope19import kotlinx.coroutines.launch20import org.ar.ar_android_video_base.api.StartRecordRequest21import org.ar.ar_android_video_base.databinding.ActivityVideoBinding22import org.ar.rtc.Constants.LOG_FILTER_DEBUG23import org.ar.rtc.IRtcEngineEventHandler24import org.ar.rtc.RtcEngine25import kotlin.coroutines.suspendCoroutine26class VideoActivity : AppCompatActivity(), View.OnClickListener {27 private val viewBinding by lazy { ActivityVideoBinding.inflate(layoutInflater) }28 private var channelId: String = ""29 private var userId: String = ""30 private lateinit var mRtcEngine: RtcEngine31 private var isMic: Boolean = false32 private var isCamera: Boolean = false33 private lateinit var videoAdapter: MemberAdapter34 private inner class RtcEvent : IRtcEngineEventHandler() {35 override fun onJoinChannelSuccess(channel: String, uid: String, elapsed: Int) {36 super.onJoinChannelSuccess(channel, uid, elapsed)37 CoroutineScope(Dispatchers.IO).launch {38 Fuel.post("/cloudRecord/start")39 .objectBody(StartRecordRequest(channel, uid))40 .response { _, response, _ ->41 if (response.isSuccessful) {42 runOnUiThread {43 Toast.makeText(44 applicationContext,45 "Start recording",46 Toast.LENGTH_SHORT47 ).show()48 }49 }50 }51 }52 runOnUiThread {53 val member = Member(uid)54 mRtcEngine.setupLocalVideo(member.getVideoCanvas(this@VideoActivity))55 videoAdapter.addData(member)56 }57 }58 override fun onFirstRemoteVideoDecoded(uid: String, width: Int, height: Int, elapsed: Int) {59 super.onFirstRemoteVideoDecoded(uid, width, height, elapsed)60 runOnUiThread {61 val member = Member(uid)62 mRtcEngine.setupRemoteVideo(member.getVideoCanvas(this@VideoActivity))63 videoAdapter.addData(member)64 }65 }66 override fun onUserOffline(uid: String, reason: Int) {67 super.onUserOffline(uid, reason)68 runOnUiThread {69 videoAdapter.remove(Member(uid))70 }71 }72 }73 override fun onCreate(savedInstanceState: Bundle?) {74 super.onCreate(savedInstanceState)75 setContentView(viewBinding.root)76 channelId = intent.getStringExtra("channelId").toString()77 userId = App.app.userId78 mRtcEngine = RtcEngine.create(this, getString(R.string.ar_appid), RtcEvent()).also {79 it.enableVideo()80 it.setEnableSpeakerphone(true)81 it.setLogFilter(LOG_FILTER_DEBUG)82 it.setLogFile(todayLogFilePath())83 }84 initView()85 joinChannel()86 }87 private fun initView() {88 viewBinding.run {89 videoAdapter = MemberAdapter(mRtcEngine!!)90 rvVideo.layoutManager = GridLayoutManager(this@VideoActivity, 2)91 rvVideo.adapter = videoAdapter92 mic.setOnClickListener(this@VideoActivity)93 camera.setOnClickListener(this@VideoActivity)94 leave.setOnClickListener(this@VideoActivity)95 }96 }97 private fun joinChannel() {98 mRtcEngine.joinChannel(getString(R.string.ar_token), channelId, "", userId)99 }100 override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {101 if (keyCode == KeyEvent.KEYCODE_BACK) {102 finish()103 return true104 }105 return super.onKeyDown(keyCode, event)106 }107 override fun onClick(p0: View?) {108 when (p0?.id) {109 R.id.mic -> {110 isMic = !isMic111 viewBinding.mic.isSelected = isMic112 mRtcEngine.muteLocalAudioStream(isMic)113 }114 R.id.camera -> {115 isCamera = !isCamera116 viewBinding.camera.isSelected = isCamera117 mRtcEngine.switchCamera()118 }119 R.id.leave -> {120 finish()121 }122 }123 }124 override fun onDestroy() {125 super.onDestroy()126 RtcEngine.destroy()127 }128}...
YouTrack.kt
Source:YouTrack.kt
1package com.xcart.prognosis.repositories2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Parameters5import com.github.kittinunf.fuel.jackson.objectBody6import com.xcart.prognosis.domain.Issue7import com.xcart.prognosis.domain.IssueCustomField8import com.xcart.prognosis.domain.UpdateIssueFieldsRequestBody9import com.xcart.prognosis.domain.User10import com.xcart.prognosis.errors.ExternalServiceError11import com.xcart.prognosis.services.AppConfiguration12import com.xcart.prognosis.transport.configure13import com.xcart.prognosis.transport.processResult14import org.slf4j.Logger15import org.springframework.beans.factory.annotation.Autowired16import org.springframework.stereotype.Repository17@Repository18class YouTrack @Autowired constructor(config: AppConfiguration, val logger:19Logger) {20 private val baseUrl: String = config.youtrackUrl + "/youtrack/api"21 private val permToken: String = config.youtrackToken22 private val issueFields: String = "id,idReadable,created,isDraft,summary," +23 "customFields(id,name,value(id,isResolved,login,minutes,name," +24 "fullName,text,avatarUrl)),reporter(id,login,fullName)"25 private val userFields: String =26 "id,login,fullName,email,name,jabberAccount,online,avatarUrl,banned,tags(id,name,untagOnResolve,updateableBy(id,name),visibleFor(name,id),owner(id,login))"27 fun fetchIssues(query: String): List<Issue> {28 return performRequest(29 "/issues", listOf(30 "fields" to issueFields,31 "query" to query32 )33 )34 }35 fun fetchIssue(issueId: String): Issue {36 return performRequest(37 "/issues/$issueId", listOf(38 "fields" to issueFields39 )40 )41 }42 fun updateIssueFields(issueId: String, fields: List<IssueCustomField>): Issue {43 return performRequest(44 url = "/issues/$issueId",45 params = listOf(46 "fields" to issueFields47 ),48 method = Method.POST,49 body = UpdateIssueFieldsRequestBody(fields)50 )51 }52 fun fetchUsers(): List<User> {53 return performRequest(54 "/users", listOf(55 "fields" to userFields,56 "\$top" to 10057 )58 )59 }60 private inline fun <reified T : Any> performRequest(61 url: String,62 params: Parameters,63 method: Method = Method.GET,64 body: Any? = null65 ): T {66 val request = Fuel.request(method, baseUrl + url, params).configure(permToken)67 if (body !== null) {68 request.objectBody(body)69 }70 try {71 return request.processResult()72 } catch (ex: Exception) {73 throw ExternalServiceError(74 "Error during communication with YouTrack API: " + ex.message,75 ex76 )77 }78 }79}...
util.kt
Source:util.kt
1package com.mktiti.fsearch.client.rest.fuel2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Parameters4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.RequestFactory.Convenience6import com.github.kittinunf.fuel.core.Response7import com.github.kittinunf.fuel.jackson.objectBody8import com.github.kittinunf.fuel.jackson.responseObject9import com.github.kittinunf.result.Result10import com.mktiti.fsearch.client.rest.ApiCallResult11private typealias FuelResp<T> = Triple<Request, Response, Result<T, FuelError>>12private typealias FuelConverter<T> = Request.() -> FuelResp<T>13internal inline fun <reified T> Convenience.getJson(path: String, params: Parameters = emptyList()): ApiCallResult<T> {14 return getJsonConv(path, params) {15 responseObject()16 }17}18private fun <T> Convenience.getJsonConv(19 path: String,20 params: Parameters,21 converter: FuelConverter<T>22): ApiCallResult<T> {23 val (_, resp, result) = get(path, params).converter()24 return when (result) {25 is Result.Success -> ApiCallResult.Success(result.value)26 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")27 }28}29internal inline fun <reified T> Convenience.postJson(path: String, body: Any): ApiCallResult<T> {30 return postJsonConv(path, body) {31 responseObject()32 }33}34private fun <T> Convenience.postJsonConv(path: String, body: Any, converter: FuelConverter<T>): ApiCallResult<T> {35 val (_, resp, result) = post(path)36 .header("Content-Type" to "application/json")37 .objectBody(body)38 .converter()39 return when (result) {40 is Result.Success -> ApiCallResult.Success(result.value)41 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")42 }43}44internal fun Convenience.postUnit(path: String, body: Any): ApiCallResult<Unit> {45 val (_, resp, result) = post(path)46 .header("Content-Type" to "application/json")47 .objectBody(body)48 .response()49 return when (result) {50 is Result.Success -> ApiCallResult.Success(Unit)51 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")52 }53}54internal fun Convenience.deleteBoolean(path: String): ApiCallResult<Boolean> {55 val (_, resp, result) = delete(path).responseObject<Boolean>()56 return when (result) {57 is Result.Success -> ApiCallResult.Success(result.value)58 is Result.Failure -> ApiCallResult.Exception(resp.statusCode, result.getException().message ?: "Unknown error")59 }60}...
ObjectBodyTest.kt
Source:ObjectBodyTest.kt
1package com.github.kittinunf.fuel2import com.fasterxml.jackson.databind.DeserializationFeature3import com.fasterxml.jackson.databind.ObjectMapper4import com.fasterxml.jackson.databind.PropertyNamingStrategy5import com.fasterxml.jackson.module.kotlin.registerKotlinModule6import com.github.kittinunf.fuel.core.Headers7import com.github.kittinunf.fuel.core.Method8import com.github.kittinunf.fuel.core.requests.DefaultRequest9import com.github.kittinunf.fuel.jackson.objectBody10import org.hamcrest.CoreMatchers.equalTo11import org.hamcrest.MatcherAssert.assertThat12import org.junit.Test13import java.net.URL14class ObjectBodyTest {15 @Test16 fun setsBodyCorrectly() {17 val expectedBody = "{\"foo\":42,\"bar\":\"foo bar\",\"fooBar\":\"foo bar\"}"18 val bodyObject = FakeObject()19 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))20 .objectBody(bodyObject)21 assertThat(expectedBody, equalTo(String(request.body.toByteArray())))22 }23 @Test24 fun setsContentTypeCorrectly() {25 val bodyObject = listOf(26 42,27 mapOf("foo" to "bar")28 )29 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))30 .objectBody(bodyObject)31 assertThat(request[Headers.CONTENT_TYPE].lastOrNull(), equalTo("application/json"))32 }33 @Test34 fun setsBodyCorrectlyWithCustomMapper() {35 val mapper = createCustomMapper()36 val expectedBody = "{\"foo\":42,\"bar\":\"foo bar\",\"foo_bar\":\"foo bar\"}"37 val bodyObject = FakeObject()38 val request = DefaultRequest(Method.POST, URL("https://test.fuel.com/body"))39 .objectBody(bodyObject, mapper = mapper)40 assertThat(expectedBody, equalTo(String(request.body.toByteArray())))41 }42 private fun createCustomMapper(): ObjectMapper {43 val mapper = ObjectMapper().registerKotlinModule()44 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)45 mapper.propertyNamingStrategy = PropertyNamingStrategy.SNAKE_CASE46 return mapper47 }48}49data class FakeObject(50 val foo: Int = 42,51 val bar: String = "foo bar",52 val fooBar: String = "foo bar"53)...
LoginController.kt
Source:LoginController.kt
1package com.github.eventdrivenecomm.orderservice.application.restapi.controllers2import com.fasterxml.jackson.databind.ObjectMapper3import com.fasterxml.jackson.module.kotlin.registerKotlinModule4import com.github.kittinunf.fuel.Fuel5import com.github.kittinunf.fuel.core.Headers6import com.github.kittinunf.fuel.core.Request7import io.javalin.http.Context8import io.javalin.http.UnauthorizedResponse9import org.slf4j.LoggerFactory10import java.nio.charset.Charset11class LoginController {12 private val logger = LoggerFactory.getLogger(LoginController::class.java)13 /**14 * A lot of refactoring to be done here:15 *16 * 1. use konfig to get url to customer-service17 * 2. maybe use async request to avoid blocking18 * 3. extract DTOs to somewhere else19 * 4. extract fuel logic to some http client utils20 *21 */22 fun login(ctx: Context) {23 val credentials = ctx.bodyAsClass(LoginDTO::class.java)24 logger.info("Validation credentials for ${credentials.email}")25 val mapper = ObjectMapper().registerKotlinModule()26 Fuel27 .post("http://localhost:7002/login")28 .objectBody(bodyObject = credentials, mapper = mapper)29 .responseString()30 .let { (request, response, result) ->31 result.fold(32 success = { result ->33 ctx.json(mapper.readValue(result, TokenDTO::class.java))34 },35 failure = { failure ->36 logger.error("Failed to get credentials: ${failure.response}")37 throw UnauthorizedResponse()38 }39 )40 }41 }42}43data class LoginDTO(44 val email: String,45 val password: String46)47data class TokenDTO(48 val token: String49)50/**51 * Set the body to an Object to be serialized52 */53fun Request.objectBody(54 bodyObject: Any,55 charset: Charset = Charsets.UTF_8,56 mapper: ObjectMapper57): Request {58 val bodyString = mapper.writeValueAsString(bodyObject)59 this[Headers.CONTENT_TYPE] = "application/json"60 return body(bodyString, charset)61}...
WalletApiGateway.kt
Source:WalletApiGateway.kt
1import com.fasterxml.jackson.databind.DeserializationFeature2import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper3import com.github.kittinunf.fuel.httpPost4import com.github.kittinunf.fuel.jackson.objectBody5import com.github.kittinunf.fuel.jackson.responseObject6import com.lesbass.wallet.infrastructure.WalletCategory7import com.natpryce.konfig.*8data class CheckUserRequest(val userName: String)9data class CategoriesRequest(val userName: String)10class WalletApiGateway {11 private val objectMapper = jacksonObjectMapper()12 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)13 private val config = EnvironmentVariables() overriding14 ConfigurationProperties.fromResource("defaults.properties")15 private fun buildApiUrl(endpoint: String): String {16 val walletApiBaseUrl = config[Key("WALLET_BASE_URL", stringType)]17 return walletApiBaseUrl + endpoint18 }19 private fun getBearer(): String {20 return """Bearer ${config[Key("WALLET_API_KEY", stringType)]}"""21 }22 fun isAuthorized(checkUserRequest: CheckUserRequest): Boolean {23 val (_, _, result) = buildApiUrl("/check-user")24 .httpPost()25 .appendHeader("Authorization", getBearer())26 .objectBody(checkUserRequest)27 .responseString()28 return result is com.github.kittinunf.result.Result.Success29 }30 fun getCategories(categoriesRequest: CategoriesRequest): List<WalletCategory> {31 val (_, _, result) = buildApiUrl("/category")32 .httpPost()33 .appendHeader("Authorization", getBearer())34 .objectBody(categoriesRequest)35 .responseObject<List<WalletCategory>>(mapper = objectMapper)36 return result.fold(37 success = { it },38 failure = { error -> throw Exception(error.message ?: "Errore generico") }39 )40 }41}...
ReplacePlaylistTracksEndpoint.kt
Source:ReplacePlaylistTracksEndpoint.kt
1package api.spotify.wrapper.endpoints.playlist.tracks.replace2import api.CredentialExtensions.refreshTokenIfRequired3import api.exception.ApiException4import api.spotify.wrapper.ApiEndpoint5import api.spotify.wrapper.endpoints.common.SpotifyError6import com.github.kittinunf.fuel.Fuel7import com.github.kittinunf.fuel.core.extensions.authentication8import com.github.kittinunf.fuel.jackson.objectBody9import com.google.api.client.auth.oauth2.Credential10import org.apache.http.HttpStatus11class ReplacePlaylistTracksEndpoint(private val credential: Credential) :12 ApiEndpoint<ReplacePlaylistTracksRequest, ReplacePlaylistTracksResponse>() {13 private val successfulStatusCodes = setOf(HttpStatus.SC_CREATED)14 override fun call(request: ReplacePlaylistTracksRequest): ReplacePlaylistTracksResponse {15 credential.refreshTokenIfRequired()16 val (_request, response, result) = Fuel.put("https://api.spotify.com/v1/playlists/${request.playlistId}/tracks")17 .authentication()18 .bearer(credential.accessToken)19 .objectBody(request)20 .responseString()21 val (content, _error) = result22 if (content == null) throw ApiException("Expected the API response to have a body")23 checkResponseStatus<SpotifyError>(content, response.statusCode, successfulStatusCodes)24 return deserialize(content)25 }26}...
AddPlaylistTracksEndpoint.kt
Source:AddPlaylistTracksEndpoint.kt
1package api.spotify.wrapper.endpoints.playlist.tracks.add2import api.CredentialExtensions.refreshTokenIfRequired3import api.exception.ApiException4import api.spotify.wrapper.ApiEndpoint5import api.spotify.wrapper.endpoints.common.SpotifyError6import com.github.kittinunf.fuel.Fuel7import com.github.kittinunf.fuel.core.extensions.authentication8import com.github.kittinunf.fuel.jackson.objectBody9import com.google.api.client.auth.oauth2.Credential10import org.apache.http.HttpStatus11class AddPlaylistTracksEndpoint(val credential: Credential) :12 ApiEndpoint<AddPlaylistTracksRequest, AddPlaylistTracksResponse>() {13 private val successfulStatusCodes = setOf(HttpStatus.SC_CREATED)14 override fun call(request: AddPlaylistTracksRequest): AddPlaylistTracksResponse {15 credential.refreshTokenIfRequired()16 val (_request, response, result) = Fuel.post("https://api.spotify.com/v1/playlists/${request.playlistId}/tracks")17 .authentication()18 .bearer(credential.accessToken)19 .objectBody(request)20 .responseString()21 val (content, _error) = result22 if (content == null) throw ApiException("Expected the API response to have a body")23 checkResponseStatus<SpotifyError>(content, response.statusCode, successfulStatusCodes)24 return deserialize(content)25 }26}...
Request.objectBody
Using AI Code Generation
1val (request, response, result) = "/posts".httpPost().objectBody(Post(1, 1, "title", "body")).responseObject<Post>()2println(request)3println(response)4println(result)5{userId=1, id=101, title=title, body=body}6val (request, response, result) = "/posts/1".httpGet().responseObject<Post>()7println(request)8println(response)9println(result)10{userId=1, id=1, title=sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body=quia et suscipit11velit sunt rem eveniet architecto}12val (request, response, result) = "/posts".httpGet().responseList<Post>()13println(request)14println(response)15println(result)16[{userId=1, id=1, title=sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body=quia et suscipit17velit sunt rem eveniet architecto}, {userId=1, id=2, title=qui est esse, body=est rerum tempore vitae sequi sint nihil
Request.objectBody
Using AI Code Generation
1val body = ObjectBody(object)2val body = ObjectBody(object, mapper)3val body = ObjectBody(object, mapper, serializer)4val body = ObjectBody(object, serializer)5val body = ObjectBody(object, serializer, mapper)6val body = ObjectBody(object, serializer, mapper, type)7val body = ObjectBody(object, type)8val body = ObjectBody(object, type, mapper)9val body = ObjectBody(object, type, mapper, serializer)
Request.objectBody
Using AI Code Generation
1Request . objectBody ( Person ( "John" , 25 ))2Request . body ( Person ( "John" , 25 ))3Request . body ( Person ( "John" , 25 ), mapper = customMapper )4Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )5Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )6Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )7Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )8Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )9Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )10Request . body ( Person ( "John" , 25 ), mapper = customMapper , type = object : TypeToken < Person >() {}.type )
Request.objectBody
Using AI Code Generation
1val json = """{"id":1,"name":"Kittinun Vantasin"}"""2.requestBody(ObjectBody(json))3.responseString()4println(request)5println(response)6println(result)7}8}9{"id":1,"name":"Kittinun Vantasin"}10Success(value={"args":{},"data":"","files":{},"form":{},"headers":{"Accept-Encoding":"gzip","Content-Length":"37","Content-Type":"application/json","Host":"httpbin.org","User-Agent":"Fuel/1.15.0"},"json":{"id":1,"name":"Kittinun Vantasin"},"origin":"
Request.objectBody
Using AI Code Generation
1 .header("Content-Type" to "application/json")2 .objectBody(Foo("bar", 42))3 .responseString()4 println(request)5 println(response)6 println(result)7 Response(http/1.1 200 OK)8 Success(text/html; charset=UTF-8, 200 OK)
Request.objectBody
Using AI Code Generation
1val json = "{ \" id \" : 1 , \" name \" : \" John \" }"2.responseString()3ObjectBody(json).toRequest(request)4val (data, error) = result5println(data)6val json = "{ \" id \" : 1 , \" name \" : \" John \" }"7.responseString()8JacksonBody(json).toRequest(request)9val (data, error) = result10println(data)11val json = "{ \" id \" : 1 , \" name \" : \" John \" }"12.responseString()13JacksonBody(json).toRequest(request)14val (data, error) = result15println(data)16val json = "{ \" id \" : 1 , \" name \" : \" John \" }"17.responseString()18JacksonBody(json).toRequest(request)19val (data, error) = result20println(data)21val json = "{ \" id \" : 1 , \" name \" : \" John \" }"22.responseString()23JacksonBody(json).toRequest(request)24val (data, error) = result25println(data)26val json = "{ \" id \" : 1 , \" name \" : \" John \" }"27.responseString()28JacksonBody(json).toRequest(request)29val (data, error) = result30println(data)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!