How to use from method of com.github.kittinunf.fuel.core.InlineDataPart class

Best Fuel code snippet using com.github.kittinunf.fuel.core.InlineDataPart.from

DataStore.kt

Source:DataStore.kt Github

copy

Full Screen

1package br.com.sthefanny.storeroom.Model2import android.content.Context3import android.util.Log4import com.github.kittinunf.fuel.*5import com.github.kittinunf.fuel.core.FileDataPart6import com.github.kittinunf.fuel.core.InlineDataPart7import com.github.kittinunf.fuel.gson.responseObject8import com.github.kittinunf.result.Result9import org.json.JSONObject10import java.io.*11object DataStore {12 val baseUrl = "http://gonzagahouse.ddns-intelbras.com.br:600"13// val baseUrl = "http://192.168.0.115:4001"14 var accessToken: String = ""15 private lateinit var myContext: Context16 fun setContext(context: Context) {17 myContext = context18 setUnitMeasurements()19 }20 var stores: MutableList<Store> = arrayListOf()21 private set22 var unitMeasurements: MutableList<UnitMeasurement> = arrayListOf()23 private set24 var products: MutableList<Product> = arrayListOf()25 private set26 fun setUnitMeasurements() {27 unitMeasurements.add(UnitMeasurement(0, "Peso"))28 unitMeasurements.add(UnitMeasurement(1, "Unidade"))29 }30 fun loadAllProducts(responseHandler : (result: ResponseModel) -> Unit?) {31 val responseModel = ResponseModel()32 val url = "$baseUrl/Product/list"33 url.httpGet().header("Content-Type", "application/json; charset=utf-8")34 .header("Authorization", accessToken)35 .responseObject<List<Product>>{ _, _, result->36 when(result){37 is Result.Failure ->{38 val message = result.getException().localizedMessage39 Log.d("Error!", "ResponseCode: $message")40 responseModel.hasError = true41 responseModel.error = message42 responseHandler.invoke(responseModel)43 }44 is Result.Success ->{45 val(data, _) = result46 if (data != null){47 clearAllItemsFromStore()48 products.addAll(data)49 responseModel.hasSuccess = true50 responseModel.success = "Success"51 responseHandler.invoke(responseModel)52 }53 }54 }55 }56 }57 fun loadAllItemsFromStore(responseHandler : (result: ResponseModel) -> Unit?) {58 val responseModel = ResponseModel()59 val url = "$baseUrl/Store/list"60 url.httpGet().header("Content-Type", "application/json; charset=utf-8")61 .header("Authorization", accessToken)62 .responseObject<List<Store>>{ _, _, result->63 when(result){64 is Result.Failure ->{65 val message = result.getException().localizedMessage66 Log.d("Error!", "ResponseCode: $message")67 responseModel.hasError = true68 responseModel.error = message69 responseHandler.invoke(responseModel)70 }71 is Result.Success ->{72 val(data, _) = result73 if (data != null){74 clearAllItemsFromStore()75 data.forEach {76 var product = getProductById(it.productId)77 var item: Store = it78 item.product = product?.name ?: ""79 stores.add(item)80 responseModel.hasSuccess = true81 responseModel.success = "Success"82 responseHandler.invoke(responseModel)83 }84 }85 }86 }87 }88 }89 fun getItemFromStore(position: Int): Store {90 return stores.get(position)91 }92 fun addItemToStore(store: Store, responseHandler : (result: ResponseModel) -> Unit?) {93 val url = "$baseUrl/Store"94 val responseModel = ResponseModel()95 val body = JSONObject()96 body.put("productId", store.productId)97 body.put("product", store.product)98 body.put("quantity", store.quantity)99 body.put("unitMea", store.unitMea)100 url.httpPost()101 .header("Content-Type", "application/json; charset=utf-8")102 .header("Authorization", accessToken)103 .body(body.toString())104 .responseObject<Store>{ _, _, result->105 when(result){106 is Result.Failure ->{107 val message = result.getException().localizedMessage108 Log.d("Error!", "ResponseCode: $message")109 responseModel.hasError = true110 responseModel.error = message111 responseHandler.invoke(responseModel)112 }113 is Result.Success ->{114 val(data, _) = result115 if (data != null){116 stores.add(data)117 responseModel.hasSuccess = true118 responseModel.success = "Item adicionado: ${data.product}"119 responseModel.createdId = data.id120 responseHandler.invoke(responseModel)121 }122 }123 }124 }125 }126 fun addImageToStore(storeId: Int, file: File, responseHandler : (result: ResponseModel) -> Unit?) {127 val url = "$baseUrl/Store/image"128 val responseModel = ResponseModel()129 val body = JSONObject()130 body.put("request.Id", storeId)131 body.put("request.File", file)132 Fuel.upload(url)133 .add(134 FileDataPart(file, name = "request.File", filename="teste.png"),135 InlineDataPart(storeId.toString(), name = "request.Id")136 )137 .header(mutableMapOf(138 "Authorization" to accessToken,139 "Content-Type" to "multipart/form-data; boundary=--------------------------353036372019982236523763")140 )141 .responseObject<Store>{ _, _, result->142 when(result){143 is Result.Failure ->{144 val message = result.getException().localizedMessage145 Log.d("Error!", "ResponseCode: $message")146 responseModel.hasError = true147 responseModel.error = message148 responseHandler.invoke(responseModel)149 }150 is Result.Success ->{151 val(data, _) = result152 if (data != null){153 stores.add(data)154 responseModel.hasSuccess = true155 responseModel.success = "Image adicionada"156 responseHandler.invoke(responseModel)157 }158 }159 }160 }161 }162 fun editItemFromStore(store: Store, responseHandler : (result: ResponseModel) -> Unit?) {163// TaskEditStore(city, delegate).execute("$baseUrl/Store")164 val responseModel = ResponseModel()165 val url = "$baseUrl/Store"166 val body = JSONObject()167 body.put("id", store.id)168 body.put("productId", store.productId)169 body.put("product", store.product)170 body.put("quantity", store.quantity)171 body.put("unitMea", store.unitMea)172 url.httpPut()173 .header("Content-Type", "application/json; charset=utf-8")174 .header("Authorization", accessToken)175 .body(body.toString())176 .responseObject<Store>{ _, _, result->177 when(result){178 is Result.Failure ->{179 val message = result.getException().localizedMessage180 Log.d("Error!", "ResponseCode: $message")181 responseModel.hasError = true182 responseModel.error = message183 responseHandler.invoke(responseModel)184 }185 is Result.Success ->{186 val(data, _) = result187 if (data != null){188 stores.add(data)189 responseModel.hasSuccess = true190 responseModel.success = "Item atualizado: ${data.product}"191 responseModel.createdId = data.id192 responseHandler.invoke(responseModel)193 }194 }195 }196 }197 }198 fun removeItemFromStore(position: Int, responseHandler : (result: ResponseModel) -> Unit?) {199// TaskRemoveStore(getItemFromStore(position), delegate).execute("$baseUrl/Store")200 val responseModel = ResponseModel()201 var item = getItemFromStore(position)202 val url = "$baseUrl/Store/${item.id}"203 url.httpDelete()204 .header("Content-Type", "application/json; charset=utf-8")205 .header("Authorization", accessToken)206 .response{ _, _, result->207 when(result){208 is Result.Failure ->{209 val message = result.getException().localizedMessage210 Log.d("Error!", "ResponseCode: $message")211 responseModel.hasError = true212 responseModel.error = message213 responseHandler.invoke(responseModel)214 }215 is Result.Success ->{216 responseModel.hasSuccess = true217 responseModel.success = "Item removido: ${item.product}"218 responseHandler.invoke(responseModel)219 }220 }221 }222 }223 fun clearAllItemsFromStore() {224 stores.clear()225 }226 fun getProduct(position: Int): Product {227 return products.get(position)228 }229 fun getProductById(id: Int): Product? {230 return products.firstOrNull { it.id == id }231 }232 fun clearAllProducts() {233 products.clear()234 }235 fun addUser(user: User, responseHandler : (result: ResponseModel) -> Unit?) {236 val url = "$baseUrl/User"237 val responseModel = ResponseModel()238 val body = JSONObject()239 body.put("name", user.name)240 body.put("email", user.email)241 body.put("password", user.password)242 url.httpPost()243 .header("Content-Type", "application/json; charset=utf-8")244 .body(body.toString())245 .responseObject<User>{ _, _, result->246 when(result){247 is Result.Failure ->{248 val message = result.getException().localizedMessage249 Log.d("Error!", "ResponseCode: $message")250 responseModel.hasError = true251 responseModel.error = message252 responseHandler.invoke(responseModel)253 }254 is Result.Success ->{255 val(data, _) = result256 if (data != null) {257 responseModel.hasSuccess = true258 responseModel.success = "Usuário criado: ${data.name}"259 responseHandler.invoke(responseModel)260 }261 }262 }263 }264 }265 fun loginUser(user: User, responseHandler : (result: ResponseModel) -> Unit?) {266 val url = "$baseUrl/User/login"267 val responseModel = ResponseModel()268 val body = JSONObject()269 body.put("email", user.email)270 body.put("password", user.password)271 url.httpPost()272 .header("Content-Type", "application/json; charset=utf-8")273 .body(body.toString())274 .responseObject<User>{ _, _, result->275 when(result){276 is Result.Failure ->{277 val message = result.getException().localizedMessage278 Log.d("Error!", "ResponseCode: $message")279 responseModel.hasError = true280 responseModel.error = message281 responseHandler.invoke(responseModel)282 }283 is Result.Success ->{284 val(data, _) = result285 if (data?.accessToken != null && data.accessToken!!.isNotEmpty()){286 accessToken = data.accessToken!!287 responseModel.hasSuccess = true288 responseModel.success = "Success"289 responseHandler.invoke(responseModel)290 }291 }292 }293 }294 }295 fun logoutUser(responseHandler : (result: ResponseModel) -> Unit?) {296 val url = "$baseUrl/User/logout"297 val responseModel = ResponseModel()298 url.httpPost()299 .header("Content-Type", "application/json; charset=utf-8")300 .header("Authorization", accessToken)301 .response{ _, _, result->302 when(result){303 is Result.Failure ->{304 val message = result.getException().localizedMessage305 Log.d("Error!", "ResponseCode: $message")306 responseModel.hasError = true307 responseModel.error = message308 responseHandler.invoke(responseModel)309 }310 is Result.Success -> {311 responseModel.hasSuccess = true312 responseModel.success = "Deslogado com sucesso"313 responseHandler.invoke(responseModel)314 }315 }316 }317 }318}...

Full Screen

Full Screen

Api.kt

Source:Api.kt Github

copy

Full Screen

1package moe.tlaster.weipo.services2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.InlineDataPart4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.ResponseDeserializable6import com.github.kittinunf.fuel.coroutines.awaitObject7import com.github.kittinunf.fuel.coroutines.awaitStringResponse8import com.github.kittinunf.fuel.httpGet9import com.github.kittinunf.fuel.httpPost10import com.github.kittinunf.fuel.httpUpload11import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf12import kotlinx.serialization.KSerializer13import kotlinx.serialization.json.Json14import kotlinx.serialization.json.JsonObject15import kotlinx.serialization.json.contentOrNull16import kotlinx.serialization.list17import moe.tlaster.weipo.services.models.*18import java.io.File19inline fun <reified T : Any> defaultKotlinxDeserializerOf(loader: KSerializer<T>): ResponseDeserializable<T> {20 return kotlinxDeserializerOf(loader, json = Json.nonstrict)21}22suspend inline fun <reified T : Any> Request.awaitObject(loader: KSerializer<T>): T {23 return this.awaitObject(defaultKotlinxDeserializerOf(loader))24}25suspend inline fun <reified T : Any> Request.awaitWeiboResponse(loader: KSerializer<T>): WeiboResponse<T> {26 return this.awaitObject(defaultKotlinxDeserializerOf(WeiboResponse.serializer(loader)))27}28suspend inline fun <reified T: Any> WeiboResponse<T>.getData(): T {29 return this.data ?: throw Error()30}31object Api {32 const val HOST = "https://m.weibo.cn"33 suspend fun timeline(maxid: Long = 0): TimelineData {34 return "$HOST/feed/friends"35 .httpGet(listOf("max_id" to maxid))36 .awaitWeiboResponse(TimelineData.serializer())37 .getData()38 }39 suspend fun mentionsAt(page: Int = 1): List<Status> {40 return "$HOST/message/mentionsAt"41 .httpGet(listOf("page" to page))42 .awaitWeiboResponse(Status.serializer().list)43 .getData()44 }45 suspend fun mentionsCmt(page: Int = 1): List<Comment> {46 return "$HOST/message/mentionsCmt"47 .httpGet(listOf("page" to page))48 .awaitWeiboResponse(Comment.serializer().list)49 .getData()50 }51 suspend fun comment(page: Int = 1): List<Comment> {52 return "$HOST/message/cmt"53 .httpGet(listOf("page" to page))54 .awaitWeiboResponse(Comment.serializer().list)55 .getData()56 }57 suspend fun attitude(page: Int = 1): List<Attitude> {58 return "$HOST/message/attitude"59 .httpGet(listOf("page" to page))60 .awaitWeiboResponse(Attitude.serializer().list)61 .getData()62 }63 suspend fun messageList(page: Int = 1): List<MessageList> {64 return "$HOST/message/msglist"65 .httpGet(listOf("page" to page))66 .awaitWeiboResponse(MessageList.serializer().list)67 .getData()68 }69 suspend fun profile(uid: Long): ProfileData {70 return "$HOST/api/container/getIndex"71 .httpGet(72 listOf(73 "type" to "uid",74 "value" to uid75 )76 )77 .awaitWeiboResponse(ProfileData.serializer())78 .getData()79 }80 suspend fun userId(name: String): Long {81 val (_, response, _) = "$HOST/n/$name"82 .httpGet()83 .awaitStringResponse()84 return "/u/(\\d+)"85 .toRegex()86 .find(response.url.toString())87 ?.let {88 it.groups[1]89 }?.let {90 it.value.toLongOrNull()91 } ?: throw Error("user not found")92 }93 suspend fun config(): Config {94 return "$HOST/api/config"95 .httpGet()96 .awaitWeiboResponse(Config.serializer())97 .getData()98 }99 suspend fun profileTab(uid: Long, containerId: String, since_id: Long = 0): JsonObject {100 return "$HOST/api/container/getIndex"101 .httpGet(listOf(102 "type" to "uid",103 "value" to uid,104 "containerid" to containerId,105 "since_id" to since_id106 ))107 .awaitWeiboResponse(JsonObject.serializer())108 .getData()109 }110 suspend fun follow(uid: Long, page: Int = 1): JsonObject {111 val param = getParamFromProfileInfo(uid, "follow")112 return "$HOST/api/container/getSecond?$param"113 .httpGet(listOf("page" to page))114 .awaitWeiboResponse(JsonObject.serializer())115 .getData()116 }117 private suspend fun getParamFromProfileInfo(uid: Long, key: String): String {118 val info = "$HOST/profile/info"119 .httpGet(120 listOf(121 "uid" to uid122 )123 )124 .awaitWeiboResponse(JsonObject.serializer())125 .getData()126 val container =127 info[key]?.contentOrNull ?: throw Error("Can not find the user profile info")128 return container.substring(container.indexOf('?') + 1)129 }130 suspend fun myFans(since_id: Long = 0): JsonObject {131 return "$HOST/api/container/getIndex"132 .httpGet(listOf(133 "containerid" to "231016_-_selffans",134 "since_id" to since_id135 ))136 .awaitWeiboResponse(JsonObject.serializer())137 .getData()138 }139 suspend fun fans(uid: Long, page: Int = 1): JsonObject {140 val param = getParamFromProfileInfo(uid, "fans")141 return "$HOST/api/container/getSecond?$param"142 .httpGet(listOf("page" to page))143 .awaitWeiboResponse(JsonObject.serializer())144 .getData()145 }146 suspend fun update(content: String, vararg pics: String): JsonObject {147 val st = config().st148 return "$HOST/api/statuses/update"149 .httpPost(listOf(150 "content" to content,151 "st" to st,152 "picId" to pics.joinToString(",")153 ))154 .header("Referer", "$HOST/compose/?${(if (pics.any()) "&pids=${pics.joinToString(",")}" else "")}")155 .awaitWeiboResponse(JsonObject.serializer())156 .getData()157 }158 suspend fun uploadPic(file: File): UploadPic {159 val st = config().st ?: throw Error()160 return "$HOST/api/statuses/uploadPic"161 .httpUpload()162 .add(InlineDataPart("json", "type"))163 .add(InlineDataPart(st, "st"))164 .add(FileDataPart(file, name = "pic", filename = file.name))165 .header("Referer", "$HOST/compose/")166 .awaitObject(UploadPic.serializer())167 }168 suspend fun repost(content: String, reply: ICanReply, picId: String? = null): JsonObject {169 val st = config().st170 return "$HOST/api/statuses/repost"171 .httpPost(listOf(172 "id" to reply.id,173 "mid" to reply.mid,174 "content" to content,175 "st" to st,176 "picId" to picId177 ))178 .header("Referer", "$HOST/compose/repost?id=${reply.id}${(if (!picId.isNullOrEmpty()) "&pids=${picId}" else "")}")179 .awaitWeiboResponse(JsonObject.serializer())180 .getData()181 }182 suspend fun reply(content: String, comment: Comment, picId: String? = null): JsonObject {183 val st = config().st184 return "$HOST/api/comments/reply"185 .httpPost(listOf(186 "id" to comment.status?.id,187 "mid" to comment.status?.id,188 "content" to content,189 "cid" to comment.id,190 "reply" to comment.id,191 "st" to st,192 "picId" to picId193 ))194 .header("Referer", "$HOST/compose/reply?id=${comment.id}${(if (!picId.isNullOrEmpty()) "&pids=${picId}" else "")}")195 .awaitWeiboResponse(JsonObject.serializer())196 .getData()197 }198 suspend fun comment(content: String, reply: ICanReply, picId: String? = null): JsonObject {199 val st = config().st200 return "$HOST/api/comments/create"201 .httpPost(listOf(202 "id" to reply.id,203 "mid" to reply.mid,204 "content" to content,205 "st" to st,206 "picId" to picId207 ))208 .header("Referer", "$HOST/compose/comment?id=${reply.id}${(if (!picId.isNullOrEmpty()) "&pids=${picId}" else "")}")209 .awaitWeiboResponse(JsonObject.serializer())210 .getData()211 }212 suspend fun repostTimeline(id: Long, page: Int = 1): RepostTimeline {213 return "$HOST/api/statuses/repostTimeline"214 .httpGet(listOf(215 "id" to id,216 "page" to page217 ))218 .awaitWeiboResponse(RepostTimeline.serializer())219 .getData()220 }221 suspend fun hotflow(id: Long, mid: Long, maxid: Long = 0): HotflowData {222 return "$HOST/comments/hotflow"223 .httpGet(listOf(224 "id" to id,225 "mid" to mid,226 "max_id" to maxid,227 "max_id_type" to 0228 ))229 .awaitWeiboResponse(HotflowData.serializer())230 .getData()231 }232 suspend fun hotflowChild(cid: Long, maxid: Long): HotflowChildData {233 return "$HOST/comments/hotFlowChild"234 .httpGet(listOf(235 "cid" to cid,236 "max_id" to maxid,237 "max_id_type" to 0238 ))239 .awaitObject(HotflowChildData.serializer())240 }241 suspend fun extend(id: Long): LongTextData {242 return "$HOST/statuses/extend"243 .httpGet(listOf(244 "id" to id245 ))246 .awaitWeiboResponse(LongTextData.serializer())247 .getData()248 }249 suspend fun storyVideoLink(pageInfoLink: String): StoryData {250 return pageInfoLink.replace("/s/video/index", "/s/video/object")251 .httpGet()252 .awaitWeiboResponse(StoryData.serializer())253 .getData()254 }255 suspend fun emoji(): EmojiData {256 return "https://weibo.com/aj/mblog/face?type=face"257 .httpGet()258 .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.16 Safari/537.36 Edg/79.0.309.15")259 .awaitObject(EmojiData.serializer())260 }261 suspend fun follow(uid: Long): User {262 val st = config().st263 return "$HOST/api/friendships/create"264 .httpPost(listOf(265 "st" to st,266 "uid" to uid267 ))268 .awaitWeiboResponse(User.serializer())269 .getData()270 }271 suspend fun unfollow(uid: Long): User {272 val st = config().st273 return "$HOST/api/friendships/destory"274 .httpPost(listOf(275 "st" to st,276 "uid" to uid277 ))278 .awaitWeiboResponse(User.serializer())279 .getData()280 }281 suspend fun unread(): UnreadData {282 return "$HOST/api/remind/unread"283 .httpGet(listOf(284 "t" to System.currentTimeMillis() / 1000285 ))286 .awaitWeiboResponse(UnreadData.serializer())287 .getData()288 }289 suspend fun chatList(uid: Long, count: Int = 10, unfollowing: Int = 0, since_id: Long = 0, is_continuous: Int = 0, max_id: Long = 0): DirectMessageData {290 return "$HOST/api/chat/list"291 .httpGet(arrayListOf(292 "uid" to uid,293 "count" to count,294 "unfollowing" to unfollowing295 ).also {296 if (since_id > 0) {297 it.add("since_id" to since_id)298 }299 if (is_continuous > 0) {300 it.add("is_continuous" to is_continuous)301 }302 if (max_id > 0) {303 it.add("max_id" to max_id)304 }305 })306 .awaitWeiboResponse(DirectMessageData.serializer())307 .getData()308 }309 suspend fun chatSend(content: String, uid: Long) : DirectMessageData {310 val st = config().st311 return "$HOST/api/chat/send"312 .httpPost(listOf(313 "st" to st,314 "uid" to uid,315 "content" to content316 ))317 .awaitWeiboResponse(DirectMessageData.serializer())318 .getData()319 }320 suspend fun chatUpload(file: File, tuid: Long): ChatUploadData {321 val st = config().st ?: throw Error()322 return "$HOST/api/chat/send"323 .httpUpload()324 .add(InlineDataPart("tuid", tuid.toString()))325 .add(InlineDataPart(st, "st"))326 .add(FileDataPart(file, name = "file", filename = file.name))327 .header("Referer", "$HOST/message/chat?uid=$tuid&name=msgbox")328 .awaitWeiboResponse(ChatUploadData.serializer())329 .getData()330 }331 suspend fun chatSend(content: String, uid: Long, fids: Long, media_type: Int = 1) : DirectMessageData {332 val st = config().st333 return "$HOST/api/chat/send"334 .httpPost(listOf(335 "st" to st,336 "uid" to uid,337 "content" to content,338 "fids" to fids,339 "media_type" to media_type340 ))341 .awaitWeiboResponse(DirectMessageData.serializer())342 .getData()343 }344}...

Full Screen

Full Screen

Zendesk.kt

Source:Zendesk.kt Github

copy

Full Screen

...247 class ZendeskResponseDeserializable2<T : ZendeskApiBody>(val responseType: KClass<out T>) :248 ResponseDeserializable<T> {249 override fun deserialize(content: String): T = when (responseType) {250 ZendeskApiBody.EmptyBody::class -> ZendeskApiBody.EmptyBody as T251 else -> gson.fromJson(content, responseType.java)252 }253 }254 private fun <T : ZendeskApiBody> ZendeskRequest<T>.run(requestConfigBlock: Request.() -> Unit = {}) =255 get(url)256 .apply(requestConfigBlock)257 .also { println(it) }258 .authentication()259 .basic(user, password)260 .responseObject(ZendeskResponseDeserializable2(responseType))261 .third262 .fold(263 { it.right() },264 {265 when (it.response.statusCode) {...

Full Screen

Full Screen

UploadRequest.kt

Source:UploadRequest.kt Github

copy

Full Screen

...75 */76 fun enableFor(request: Request) = request.enabledFeatures77 .getOrPut(FEATURE) {78 UploadRequest(request)79 .apply { this.body(UploadBody.from(this)) }80 .apply { this.ensureBoundary() }81 } as UploadRequest82 }83 @Deprecated("Use request.add({ BlobDataPart(...) }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)84 fun blobs(@Suppress("DEPRECATION") blobsCallback: (Request, URL) -> Iterable<Blob>): UploadRequest =85 throw NotImplementedError("request.blobs has been removed. Use request.add({ BlobDataPart(...) }, { ... }, ...) instead.")86 @Deprecated("Use request.add { BlobDataPart(...) } instead", ReplaceWith("add(blobsCallback)"))87 fun blob(@Suppress("DEPRECATION") blobCallback: (Request, URL) -> Blob): UploadRequest =88 throw NotImplementedError("request.blob has been removed. Use request.add { BlobDataPart(...) } instead.")89 @Deprecated("Use request.add({ ... }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)90 fun dataParts(dataPartsCallback: (Request, URL) -> Iterable<DataPart>): UploadRequest =91 throw NotImplementedError("request.dataParts has been removed. Use request.add { XXXDataPart(...) } instead.")92 @Deprecated("Use request.add({ FileDataPart(...) }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)93 fun sources(sourcesCallback: (Request, URL) -> Iterable<File>): UploadRequest =...

Full Screen

Full Screen

TestPrograms.kt

Source:TestPrograms.kt Github

copy

Full Screen

...103 str.append("-- Finished\n")104 return str.toString()105 }106}107// Data class to store results given from reference compiler108// Note the names of the fields have to stay the same (as these are predefined109// by the reference compiler)110data class CompilerOutput(val test: String, val upload: String, val compiler_out: String)...

Full Screen

Full Screen

ReferenceCompilerAPI.kt

Source:ReferenceCompilerAPI.kt Github

copy

Full Screen

...53 .joinLines()54 val code = try {55 out.last { "The exit code is" in it }.filter { str -> str.isDigit() }.toInt()56 } catch (e: Exception) {57 System.err.println("Could not parse exit code from reference compiler. Output:\n${out.joinLines()}\n")58 -159 }60 val progLines = prog.readLines()61 val jvmSpecOut = progLines62 .extractFromDelimiters(jvmOutTokenBegin, jvmOutTokenEnd)63 .map { it.drop(2) }64 .joinLines()65 .noneIfEmpy()66 .orNull()67 val armSpecOut = progLines68 .extractFromDelimiters(armOutTokenBegin, armOutTokenEnd)69 .map { it.drop(2) }70 .joinLines()71 .noneIfEmpy()72 .orNull()73 return RefAnswer(assembly, runtimeOut, code, jvmSpecOut, armSpecOut)74 }75 private fun Iterable<String>.extractFromDelimiters(beg: String, end: String, dropInitial: Int = 1) =76 asSequence()77 .dropWhile { beg !in it }78 .drop(dropInitial)79 .takeWhile { end !in it }80 override fun emulate(prog: String, filePath: String, input: String): Pair<String, Int> {81 val emulatorUrl = "https://teaching.doc.ic.ac.uk/wacc_compiler/emulate.cgi"82 val newFile = filePath.replace(".wacc", ".s")83 val armFile = File(newFile).apply { writeText(prog) }84 val reply = queryReference<EmulatorReply>(armFile, emulatorUrl, stdin = input)85 .getOrElse { System.err.println("Failed to reach the reference emulator"); assumeTrue(false); NOT_REACHED() }86 if (reply.assemble_out.isNotBlank()) {87 val asmWithLines = prog.lines().mapIndexed { i, s ->88 val lNo = (i + 1).toString()89 lNo + " ".drop(lNo.length) + s90 }.joinLines()91 throw IllegalStateException("Failed to assemble program with error:\n${reply.assemble_out}\n$asmWithLines")92 }93 return reply.emulator_out to reply.emulator_exit.toInt()94 }95 private inline fun <reified T : Any> queryReference(f: File, url: String, stdin: String = "", vararg ops: String) =96 ops.asSequence()97 .map { InlineDataPart(it, "options[]") }98 .toList().toTypedArray()99 .let { options ->100 Fuel.upload(url)101 .add(FileDataPart(f, "testfile", f.name, "application/octet-stream"))102 .add(*options)103 .apply { if (stdin.isNotBlank()) add(InlineDataPart(stdin, "stdin")) }104 .responseObject<T>(gson).third105 .component1()106 .toOption()107 }108}109/**110 * Represents an answer from the reference compiler.[out] represents the compiled assembly,111 * or the received errors.112 */113data class RefAnswer(114 val assembly: String,115 val out: String,116 val code: Int,117 val jvmSpecificOut: String?,118 val armSpecificOut: String?119)120/**121 * Serialised JSON produced by the reference emulator122 */123data class EmulatorReply(124 val test: String,...

Full Screen

Full Screen

HdfsSendNHSO.kt

Source:HdfsSendNHSO.kt Github

copy

Full Screen

...89 .body(loginBody)90 .response()91 check(response.statusCode == 200) { "Cannot 200 status is ${response.statusCode}" }92 val data = String(response.data)93 val tokenBody = GsonJerseyProvider.hiiGson.fromJson(data, TokenBody::class.java)!!94 accessToken = tokenBody.token95 }96 return accessToken97 }98 private val tokenExpire: Boolean99 get() {100 val tokenBody = TokenBody(accessToken).toJson()101 val (_, response, _) = Fuel.post("${endPoint}auth-jwt-verify")102 .header("Content-Type" to "application/json")103 .body(tokenBody)104 .response()105 return response.statusCode != 200106 }107}...

Full Screen

Full Screen

CurseForgeClient.kt

Source:CurseForgeClient.kt Github

copy

Full Screen

...62 }63 }64 suspend fun getGameDependencies(): List<CurseForgeGameDependency> {65 // TODO: Currently this API endpoint is broken66 logger.info("Fetching game dependencies from CurseForge")67 return Json.decodeFromString(httpGet("/api/game/dependencies"))68 }69 suspend fun getGameVersions(): List<CurseForgeGameVersion> {70 logger.info("Fetching game versions from CurseForge")71 return Json.decodeFromString(httpGet("/api/game/versions"))72 }73 suspend fun uploadDist(jarFile: File, metadata: CurseForgeUploadMetadata) {74 logger.info("Uploading file to CurseForge, file=${jarFile}, metadata=${metadata}")75 val (_, response, result) = "https://minecraft.curseforge.com/api/projects/${LUCKY_BLOCK_PROJECT_ID}/upload-file"76 .httpUpload()77 .add(FileDataPart.from(jarFile.path, name="file"))78 .add(InlineDataPart(Json.encodeToString(metadata), contentType = "application/json", name = "metadata"))79 .header(mapOf("X-Api-Token" to token))80 .awaitStringResponseResult()81 when (result) {82 is Result.Failure -> {83 logger.severe(String(response.data))84 throw result.getException()85 }86 is Result.Success -> return87 }88 }89}...

Full Screen

Full Screen

from

Using AI Code Generation

copy

Full Screen

1 fun toByteArray(): ByteArray {2 val bos = ByteArrayOutputStream()3 bos.write("--".toByteArray())4 bos.write(boundary.toByteArray())5 bos.write("\r6".toByteArray())7 bos.write("Content-Disposition: form-data; name=\"".toByteArray())8 bos.write(name.toByteArray())9 bos.write("\"; filename=\"".toByteArray())10 bos.write(fileName.toByteArray())11 bos.write("\"\r12".toByteArray())13 bos.write("Content-Type: ".toByteArray())14 bos.write(contentType.toByteArray())15 bos.write("\r16".toByteArray())17 bos.write(data)18 bos.write("\r19".toByteArray())20 bos.write("--".toByteArray())21 bos.write(boundary.toByteArray())22 bos.write("--\r23".toByteArray())24 return bos.toByteArray()25 }

Full Screen

Full Screen

from

Using AI Code Generation

copy

Full Screen

1fun inlineDataPart(2): Part = InlineDataPart(data, name, filename, contentType)3fun inlineDataPart(4): Part = InlineDataPart(data, name, filename, contentType)5fun inlineDataPart(6): Part = InlineDataPart(data, name, filename, contentType)7fun inlineDataPart(8): Part = InlineDataPart(data, name, filename, contentType)9fun inlineDataPart(10): Part = InlineDataPart(data, name, filename, contentType)11fun inlineDataPart(12): Part = InlineDataPart(data, name, filename, contentType)13fun inlineDataPart(14): Part = InlineDataPart(data, name, filename, contentType)15fun inlineDataPart(16): Part = InlineDataPart(data

Full Screen

Full Screen

from

Using AI Code Generation

copy

Full Screen

1val data = InlineDataPart("hello", "world")2val data = InlineDataPart("hello", "world", "text/plain")3val data = InputStreamPart("hello", "world".byteInputStream())4val data = InputStreamPart("hello", "world".byteInputStream(), "text/plain")5val data = InputStreamPart("hello", "world".byteInputStream(), "text/plain", name = "world.txt")6val data = FilePart("hello", File("world.txt"))7val data = FilePart("hello", File("world.txt"), "text/plain")8val data = FilePart("hello", File("world.txt"), "text/plain", name = "world.txt")9val data = FileDataPart("hello", FileData("world.txt"))10val data = FileDataPart("hello", FileData("world.txt"), "text/plain")11val data = FileDataPart("hello", FileData("world.txt"), "text/plain", name = "world.txt")12val data = DataPart("hello", "world".toByteArray())13val data = DataPart("hello", "world".toByteArray(), "text/plain")14val data = DataPart("hello", "world".toByteArray(), "text/plain", name = "world.txt")15val data = DataPart("hello", "world".toByteArray())16val data = DataPart("hello", "world".toByteArray(), "text/plain")17val data = DataPart("hello", "world".toByteArray(), "text/plain", name = "world.txt")18val data = DataPart("hello", "world".toByteArray())19val data = DataPart("hello", "world".toByteArray(), "text/plain")20val data = DataPart("hello", "world".toByteArray(), "text/plain", name = "world.txt")

Full Screen

Full Screen

from

Using AI Code Generation

copy

Full Screen

1val data = InlineDataPart("data", "value", "text/plain")2val data = InlineDataPart("data", "value", "text/plain", "data.txt")3val data = InlineDataPart("data", "value", "text/plain", "data.txt", "UTF-8")4val data = InlineDataPart("data", "value", "text/plain", "data.txt", "UTF-8", "attachment")5val data = InlineDataPart("data", "value", "text/plain", "data.txt", "UTF-8", "attachment", mapOf("key" to "value"))6val data = FileDataPart(File("path/to/file"), "text/plain")7val data = FileDataPart(File("path/to/file"), "text/plain", "UTF-8")8val data = FileDataPart(File("path/to/file"), "text/plain", "UTF-8", "attachment")9val data = FileDataPart(File("path/to/file"), "text/plain", "UTF-8", "attachment", mapOf("key" to "value"))10val data = InputStreamDataPart("data", "value", "text/plain")11val data = InputStreamDataPart("data", "value", "text/plain", "data.txt")12val data = InputStreamDataPart("data", "value", "text/plain", "data.txt", "UTF-8")13val data = InputStreamDataPart("data", "value", "text/plain", "data.txt", "UTF-8", "attachment")14val data = InputStreamDataPart("data", "value", "text/plain", "data.txt", "UTF-8", "attachment", mapOf("key" to "value"))15val data = StringDataPart("data", "value", "text/plain")16val data = StringDataPart("data", "value", "text/plain", "data.txt")17val data = StringDataPart("data", "value", "text/plain", "data.txt", "UTF-8")18val data = StringDataPart("data", "value", "text/plain", "data.txt", "UTF-8",

Full Screen

Full Screen

from

Using AI Code Generation

copy

Full Screen

1class InlineDataPart(2) : Part {3 constructor(name: String, filename: String, contentType: String, data: String) : this(name, filename, contentType, data.toByteArray())4 override fun getHeaders(): Map<String, String> {5 return mapOf(6 "Content-Disposition" to "form-data; name=\"$name\"; filename=\"$filename\"",7 }8 override fun getData(): ByteArray {9 }10}11fun uploadFile(12) {13 val part = InlineDataPart(name, fileName, contentType, file.readBytes())14 Fuel.upload(url, listOf(part))15 .response { _, _, result ->16 result.fold(17 { println("Success: $it") },18 { println("Failure: $it") }19 }20}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in InlineDataPart

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful