Best Fuel code snippet using com.github.kittinunf.fuel.core.InlineDataPart
Api.kt
Source:Api.kt
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_type...
Zendesk.kt
Source:Zendesk.kt
...31import arrow.core.toOption32import arrow.core.toT33import com.github.kittinunf.fuel.Fuel34import com.github.kittinunf.fuel.core.FileDataPart35import com.github.kittinunf.fuel.core.InlineDataPart36import com.github.kittinunf.fuel.core.Method37import com.github.kittinunf.fuel.core.Method.DELETE38import com.github.kittinunf.fuel.core.Method.GET39import com.github.kittinunf.fuel.core.Method.POST40import com.github.kittinunf.fuel.core.Method.PUT41import com.github.kittinunf.fuel.core.Request42import com.github.kittinunf.fuel.core.ResponseDeserializable43import com.github.kittinunf.fuel.core.extensions.authentication44import com.github.kittinunf.fuel.core.extensions.jsonBody45import com.github.kittinunf.fuel.core.requests.UploadRequest46import com.github.kittinunf.fuel.core.requests.upload47import com.saagie.htmltozendeskuploader.model.Article48import com.saagie.htmltozendeskuploader.model.ArticleAttachment49import com.saagie.htmltozendeskuploader.model.ExistingSection50import com.saagie.htmltozendeskuploader.model.NewSection51import com.saagie.htmltozendeskuploader.model.Translation52import com.saagie.htmltozendeskuploader.zendesk.HtmlToZendeskError.ZendeskRequestError.ResourceDoesNotExist53import com.saagie.htmltozendeskuploader.zendesk.HtmlToZendeskError.ZendeskRequestError.UnexpectedRequestError54import com.saagie.htmltozendeskuploader.zendesk.HtmlToZendeskError.ZendeskRequestError.UnexpectedRequestResult55import com.saagie.htmltozendeskuploader.zendesk.ZendeskRequest.DeleteSection56import java.io.File57import kotlin.reflect.KClass58sealed class ZendeskApiBody {59 data class SectionsBody(val sections: List<ExistingSection>) : ZendeskApiBody()60 data class NewSectionBody(val section: NewSection) : ZendeskApiBody()61 data class ExistingSectionBody(val section: ExistingSection) : ZendeskApiBody()62 data class ArticleBody(val article: Article) : ZendeskApiBody()63 data class ArticlesBody(val articles: List<Article>) : ZendeskApiBody()64 data class TranslationBody(val translation: Translation) : ZendeskApiBody()65 data class TranslationsBody(val translations: List<Translation>) : ZendeskApiBody()66 data class AttachmentIdsBody(val attachmentIds: List<Long>) : ZendeskApiBody()67 data class AttachmentBody(val articleAttachment: ArticleAttachment) : ZendeskApiBody()68 object EmptyBody : ZendeskApiBody()69}70sealed class ZendeskRequest<out T : ZendeskApiBody>(71 val method: Method,72 val path: String,73 val responseType: KClass<out T>,74 open val body: ZendeskApiBody = ZendeskApiBody.EmptyBody75) {76 open fun get(basePath: String) = Fuel.request(method, basePath + path, null)77 .apply {78 this@ZendeskRequest.body.toOption().map { jsonBody(gson.toJson(it)) }79 }80 data class GetSections(val categoryId: Long) : ZendeskRequest<ZendeskApiBody.SectionsBody>(81 GET, "/categories/$categoryId/sections.json", ZendeskApiBody.SectionsBody::class82 )83 data class CreateSection(val categoryId: Long, val section: NewSection) :84 ZendeskRequest<ZendeskApiBody.ExistingSectionBody>(85 POST,86 "/categories/$categoryId/sections.json",87 ZendeskApiBody.ExistingSectionBody::class,88 ZendeskApiBody.NewSectionBody(section)89 )90 data class DeleteSection(val sectionId: Long) : ZendeskRequest<ZendeskApiBody.EmptyBody>(91 DELETE,92 "/sections/$sectionId.json",93 ZendeskApiBody.EmptyBody::class94 )95 data class CreateArticle(val article: Article) : ZendeskRequest<ZendeskApiBody.ArticleBody>(96 POST,97 "/sections/${article.parentSectionId}/articles.json",98 ZendeskApiBody.ArticleBody::class,99 ZendeskApiBody.ArticleBody(article)100 )101 data class GetArticles(val sectionId: Long) : ZendeskRequest<ZendeskApiBody.ArticlesBody>(102 GET,103 "/sections/$sectionId/articles.json",104 ZendeskApiBody.ArticlesBody::class105 )106 data class UploadAttachedImage(val filePath: String) : ZendeskRequest<ZendeskApiBody.AttachmentBody>(107 POST,108 "/articles/attachments.json",109 ZendeskApiBody.AttachmentBody::class110 ) {111 override fun get(basePath: String): UploadRequest = super.get(basePath).upload()112 .add(FileDataPart(name = "file", file = File(filePath)))113 .add(InlineDataPart(name = "inline", content = "true"))114 }115 data class LinkAttachedImage(val articleId: Long, val attachmentIds: List<Long>) :116 ZendeskRequest<ZendeskApiBody.EmptyBody>(117 POST,118 "/articles/$articleId/bulk_attachments.json",119 ZendeskApiBody.EmptyBody::class,120 ZendeskApiBody.AttachmentIdsBody(attachmentIds)121 )122 data class GetArticleTranslations(val articleId: Long, val locale: String) :123 ZendeskRequest<ZendeskApiBody.TranslationsBody>(124 GET,125 "/articles/$articleId/translations.json",126 ZendeskApiBody.TranslationsBody::class127 )...
UploadRequest.kt
Source:UploadRequest.kt
...94 throw NotImplementedError("request.sources has been removed. Use request.add({ BlobDataPart(...) }, { ... }, ...) instead.")95 @Deprecated("Use request.add { FileDataPart(...)} instead", ReplaceWith("add(sourceCallback)"), DeprecationLevel.ERROR)96 fun source(sourceCallback: (Request, URL) -> File): UploadRequest =97 throw NotImplementedError("request.source has been removed. Use request.add { FileDataPart(...) } instead.")98 @Deprecated("Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead", ReplaceWith(""), DeprecationLevel.ERROR)99 fun name(nameCallback: () -> String): UploadRequest =100 throw NotImplementedError("request.name has been removed. Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead")101 @Deprecated("Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead", ReplaceWith(""), DeprecationLevel.ERROR)102 fun name(newName: String): UploadRequest =103 throw NotImplementedError("request.name has been removed. Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead")104}105fun Request.upload(): UploadRequest = UploadRequest.enableFor(this)...
TestPrograms.kt
Source:TestPrograms.kt
1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.InlineDataPart4import com.github.kittinunf.fuel.gson.responseObject5import com.google.gson.Gson6import compiler.Compiler7import org.junit.jupiter.api.Assertions.assertEquals8import org.junit.jupiter.api.TestFactory9import org.junit.jupiter.api.DynamicTest10import java.io.File11import java.lang.StringBuilder12class TestPrograms {13 private val testDirsPath = "./src/test/kotlin/testDirs"14 private val examplesPath = "./wacc_examples/"15 private val gson by lazy { Gson() }16 // All directories specified in the testDirs file17 private val allTestDirs = File(testDirsPath).readLines()18 // All files in directories in allTestDirs (recursive)19 private val testFiles = allTestDirs20 .map { dir ->21 File(examplesPath + dir).walk()22 .filter { ".wacc" in it.path }.toSortedSet()23 }.flatten()24 private fun runTest(inputFile: File) {25 println(inputFile.canonicalPath)26 val compiler = Compiler(inputFile.canonicalPath, true)27 val ret = compiler.compile()28 when {29 inputFile.canonicalPath.contains("syntax") -> assertEquals(100, ret)30 inputFile.canonicalPath.contains("semantic") -> assertEquals(200, ret)31 inputFile.canonicalPath.contains("valid") -> assertEquals(0, ret)32 }33 if(System.getProperty("test.type") == "backend") {34 runBackendTests(inputFile)35 }36 }37 @TestFactory38 fun createTests(): List<DynamicTest> {39 val files = when (System.getProperty("test.type")) {40 "syntax" -> testFiles.filter { it.absolutePath.contains("/syntaxErr/") }41 "semantic" -> testFiles.filter { it.absolutePath.contains("/semanticErr/") }42 "valid" -> testFiles.filter { it.absolutePath.contains("/valid/") }43 "backend" -> testFiles.filter { it.absolutePath.contains("/valid/") }44 else -> testFiles45 }46 return files.map { f -> DynamicTest.dynamicTest(f.name) { runTest(f) } }47 }48 private fun runBackendTests(inputFile: File) {49 val assemblyName = inputFile.name.replace(".wacc", ".s")50 val executableName = inputFile.nameWithoutExtension51 // Create the executable file52 Runtime.getRuntime()53 .exec("arm-linux-gnueabi-gcc -o ./$executableName -mcpu=arm1176jzf-s -mtune=arm1176jzf-s ./$assemblyName").waitFor()54 val assemblyFile = File("./$assemblyName")55 val executableFile = File("./$executableName")56 // Get the value we should pass to stdin57 val stdinDataName = "./wacc_examples/inputs/${inputFile.name.replace(".wacc", ".input")}"58 // Get input for IO tests59 var stdin = ""60 if(File(stdinDataName).exists()) {61 stdin = File(stdinDataName).readText()62 }63 // Run QEMU on the created executable file64 val qemu = ProcessBuilder("/bin/sh", "-c", "echo $stdin | qemu-arm -L /usr/arm-linux-gnueabi/ $executableName").start()65 val exitCode = qemu.waitFor().toString()66 // Read the content produced by qemu67 val outputContent = StringBuilder()68 qemu.inputStream.reader().use {69 outputContent.append(it.readText())70 }71 // Cache the file if isn't already cached to reduce HTTP overhead72 val cachedName = "./wacc_examples/cached_outputs/${inputFile.name.replace(".wacc", "")}.output"73 val cachedFile = File(cachedName)74 if(!cachedFile.exists()) {75 // Contact the reference compiler using Fuel and gson76 val referenceCompiler =77 Fuel.upload("https://teaching.doc.ic.ac.uk/wacc_compiler/run.cgi")78 .add(FileDataPart(inputFile, "testfile", inputFile.name, "text/plain"))79 .add(InlineDataPart("-x","options[]"))80 .add(InlineDataPart(stdin, "stdin"))81 .responseObject<CompilerOutput>(gson)82 .third83 .component1()!!84 cachedFile.writeText(referenceCompiler.compiler_out)85 }86 val expectedContent = cachedFile.readText()87 val actualContent = formatToReferenceStyle(outputContent.toString(), exitCode)88 // Done with the files. Delete them.89 assemblyFile.delete()90 executableFile.delete()91 assertEquals(expectedContent, actualContent)92 }93 // Helper function to match style of reference compiler94 private fun formatToReferenceStyle(outputContent: String, exitCode: String): String {...
ReferenceCompilerAPI.kt
Source:ReferenceCompilerAPI.kt
...3import arrow.core.getOrElse4import arrow.core.toOption5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.core.FileDataPart7import com.github.kittinunf.fuel.core.InlineDataPart8import com.github.kittinunf.fuel.gson.responseObject9import com.google.gson.Gson10import ic.org.util.NOT_REACHED11import ic.org.util.createWithDirs12import ic.org.util.joinLines13import ic.org.util.noneIfEmpy14import java.io.File15import org.junit.jupiter.api.Assumptions.assumeTrue16interface ReferenceEmulatorAPI {17 fun emulate(prog: String, filePath: String, input: String): Pair<String, Int>18}19object ReferenceCompilerAPI : ReferenceEmulatorAPI {20 private val gson by lazy { Gson() }21 private const val noCacheToken = "NO_CACHE"22 private const val jvmOutTokenBegin = "begin JVM_Output"23 private const val jvmOutTokenEnd = "end JVM_Output"24 private const val armOutTokenBegin = "begin ARM_Output"25 private const val armOutTokenEnd = "end ARM_Output"26 private const val delimiters = "==========================================================="27 fun ask(prog: File, input: String): RefAnswer {28 val emulatorUrl = "https://teaching.doc.ic.ac.uk/wacc_compiler/run.cgi"29 val cachedName = prog.absolutePath30 .replace("wacc_examples", ".test_cache")31 .replace(".wacc", ".temp")32 val cached = File(cachedName)33 val out =34 if (noCacheToken !in prog.path && cached.exists() && cached.readText().isNotBlank())35 cached.readLines()36 .also { println("Reading cached query...") }37 else38 queryReference<CompilerReply>(prog, emulatorUrl, input, "-x", "-a")39 .getOrElse { System.err.println("Failed to reach the reference emulator"); assumeTrue(false); NOT_REACHED() }40 .compiler_out.split("\n")41 .toList()42 .also { cached.createWithDirs() }43 .also { cached.writeText(it.joinLines()) }44 val assembly = out45 .extractFromDelimiters(delimiters, delimiters)46 .map { str -> str.dropWhile { chr -> chr.isDigit() }.trim() }47 .filter { it.isNotBlank() }48 .toList()49 .joinLines()50 val runtimeOut = out51 .extractFromDelimiters("-- Executing...", "The exit code is", 2)52 .map { if (delimiters in it) it.replace(delimiters, "") else it }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?,...
HdfsSendNHSO.kt
Source:HdfsSendNHSO.kt
...15 * limitations under the License.16 */17package hii.thing.api.sendnhso18import com.github.kittinunf.fuel.Fuel19import com.github.kittinunf.fuel.core.InlineDataPart20import com.github.kittinunf.fuel.core.Method21import hii.thing.api.config.GsonJerseyProvider22import hii.thing.api.config.toJson23class HdfsSendNHSO(endPoint: String = nhsoEndpoint) : SendNHSO {24 private val endPoint: String = if (endPoint.endsWith("/")) endPoint else "$endPoint/"25 companion object {26 private var accessToken: String = ""27 }28 override fun send(29 message: SendMessage,30 autoMkdir: Boolean,31 ret: (Boolean) -> Unit32 ) {33 Thread {34 val time = message.time35 val dirPath = "v1/nstda/kiosk/raw/${time.year}/${time.monthValue}/"36 val fileName = "${time.dayOfMonth}.csv"37 val csv = message.toCsv()38 append(dirPath, fileName, csv) {39 if (!it) { // à¸à¹à¸² append à¹à¸¡à¹à¸ªà¸³à¹à¸£à¹à¸40 if (autoMkdir) mkdir(dirPath)41 val createStatus = createFile("$dirPath$fileName", csv)42 ret(createStatus)43 } else44 ret(true)45 }46 }.start()47 }48 private fun mkdir(dirPath: String) {49 val dirApi = "$endPoint$dirPath?op=MKDIRS"50 Fuel.put(dirApi) // Create dir.51 .header(authHeader)52 .response()53 }54 private fun createFile(firePath: String, message: String): Boolean {55 val createApi = "$endPoint$firePath?op=CREATE"56 val dataPart = createMessageBody(message)57 val (_, response, _) = Fuel.upload(createApi, Method.PUT)58 .add(dataPart)59 .header(authHeader)60 .response()61 return response.statusCode == 20162 }63 private fun append(dirPath: String, fileName: String, message: String, ret: (Boolean) -> Unit) {64 val appendApi = "$endPoint$dirPath$fileName?op=APPEND"65 val dataPart = createMessageBody(message)66 val (_, appendResponse, _) = Fuel.upload(appendApi)67 .add(dataPart)68 .header(authHeader)69 .response()70 val length = appendResponse.body().length71 val statusCode = appendResponse.statusCode72 if (statusCode == 200 && length!! == 0L) ret(true)73 else ret(false)74 }75 private fun createMessageBody(message: String) =76 InlineDataPart(77 content = message,78 name = "file",79 contentType = "multipart/form-data; charset=UTF-8",80 filename = "file"81 )82 private val authHeader: Pair<String, String> = "Authorization" to "JWT $token"83 val token: String84 get() {85 if (tokenExpire) {86 val loginBody = LoginBody(nhsoUsername, nhsoPassword).toJson()87 val (_, response, _) = Fuel.post("${endPoint}auth-jwt")88 .header("Content-Type" to "application/json")89 .body(loginBody)90 .response()...
CurseForgeClient.kt
Source:CurseForgeClient.kt
1package mod.lucky.tools.uploadToCurseForge2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.InlineDataPart4import kotlinx.serialization.*5import kotlinx.serialization.json.*6import com.github.kittinunf.fuel.httpGet7import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult8import com.github.kittinunf.fuel.httpUpload9import com.github.kittinunf.result.Result10import java.io.File11import java.util.logging.Logger12@Serializable13data class CurseForgeGameDependency(14 val id: Int,15 val name: String,16 val slug: String,17)18@Serializable19data class CurseForgeGameVersion(20 val id: Int,21 val gameVersionTypeID: Int,22 val name: String,23 val slug: String,24)25enum class CurseForgeGameVersionType(val id: Int) {26 MINECRAFT(1),27 JAVA(2),28 FORGE(3),29 FABRIC_LOADER(73247),30 LOADER_TYPE(68441), // Forge, Fabric, Rift31}32fun getCurseForgeLoaderType(loader: LuckyBlockLoader): String {33 return when(loader) {34 LuckyBlockLoader.FORGE -> "Forge"35 LuckyBlockLoader.FABRIC -> "Fabric"36 }37}38@Serializable39data class CurseForgeUploadMetadata(40 val changelog: String, // Can be HTML or markdown if changelogType is set.41 val changelogType: String = "text", // One of "text", "html", "markdown"42 val displayName: String? = null, // Optional: A friendly display name used on the site if provided.43 val parentFileID: Int? = null, // Optional: The parent file of this file.44 val gameVersions: List<Int>, // A list of supported game versions, see the Game Versions API for details. Not supported if parentFileID is provided.45 val releaseType: String, // One of "alpha", "beta", "release".46)47class CurseForgeClient(private val token: String) {48 private val logger = Logger.getLogger(this.javaClass.name)49 private val LUCKY_BLOCK_PROJECT_ID = 57682550 suspend fun httpGet(endpoint: String): String {51 val (_, _, result) = "https://minecraft.curseforge.com${endpoint}"52 .httpGet()53 .header(mapOf("X-Api-Token" to token))54 .awaitStringResponseResult()55 when (result) {56 is Result.Failure -> {57 throw result.getException()58 }59 is Result.Success -> {60 return result.get()61 }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}...
Service.kt
Source:Service.kt
1package ktxdev.b0mb3r.service2import com.github.kittinunf.fuel.core.DataPart3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.InlineDataPart5import com.github.kittinunf.fuel.core.Response6import ktxdev.b0mb3r.phone.Phone7import ktxdev.b0mb3r.utils.jsonify8import kotlin.concurrent.thread9import com.github.kittinunf.fuel.core.Method.POST10import com.github.kittinunf.fuel.core.extensions.authenticate11import com.github.kittinunf.fuel.core.extensions.authentication12enum class Method {13 GET, POST, FORM14}15class Service(16 private val request: Request,17 private val requestBuilder: Request.(phone: Phone) -> Unit18) {19 fun request(manager: FuelManager, phone: Phone, fn: Request.(Response?) -> Unit){20 request.apply {21 requestBuilder(phone)22 if(disable){23 fn(null)24 } else {25 thread {26 val (_, response, _) = when (method) {27 Method.POST -> manager.post(url, params.toList())28 Method.GET -> manager.get(url, params.toList())29 Method.FORM -> manager.upload(url, POST).apply {30 if(params.isEmpty()) {31 for ((name, value) in formData)32 add(InlineDataPart(value.first, name, contentType = value.second))33 } else {34 parameters = params.toList()35 }36 }37 }.let {38 it.body(body?.jsonify() ?: return@let it)39 }.header(headers).let {40 it.appendHeader("Content-Type" to (contentType ?: return@let it))41 }.response()42 fn(response)43 }44 }45 }46 }...
InlineDataPart
Using AI Code Generation
1import com.github.kittinunf.fuel.core.DataPart2val dataPart = DataPart(File("path/to/file"), "image/png")3import com.github.kittinunf.fuel.core.DataPart4val dataPart = DataPart(File("path/to/file"), "image/png", "customFileName.png")5import com.github.kittinunf.fuel.core.DataPart6val dataPart = DataPart(File("path/to/file"), "image/png", "customFileName.png", "customContentDisposition")7import com.github.kittinunf.fuel.core.DataPart8val dataPart = DataPart(File("path/to/file"), "image/png", "customFileName.png", "customContentDisposition", mapOf("customHeaderKey" to "customHeaderValue"))9import com.github.kittinunf.fuel.core.DataPart10val dataPart = DataPart(File("path/to/file"), "image/png", "customFileName.png", "customContentDisposition", mapOf("customHeaderKey" to "customHeaderValue"), "customCharset")11import com.github.kittinunf.fuel.core.DataPart12val dataPart = DataPart(File("path/to/file"), "image/png", "customFileName.png", "customContentDisposition", mapOf("customHeaderKey" to "customHeaderValue"), "customCharset", "customTransferEncoding")13import com.github.kittinunf.fuel.core.DataPart14val dataPart = DataPart(File("path/to/file"), "image/png", "customFileName.png", "customContentDisposition", mapOf("customHeaderKey" to "customHeaderValue"), "customCharset", "customTransferEncoding", "customContentId")15import com.github.kittinunf.fuel.core
InlineDataPart
Using AI Code Generation
1import com.github.kittinunf.fuel.core.InlineDataPart2val data = InlineDataPart("This is some data", "data.txt", "text/plain")3val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.response()4import com.github.kittinunf.fuel.core.FileDataPart5val data = FileDataPart(File("data.txt"), "text/plain")6val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.response()7import com.github.kittinunf.fuel.core.ByteArrayDataPart8val data = ByteArrayDataPart("This is some data".toByteArray(), "data.txt", "text/plain")9val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.response()10import com.github.kittinunf.fuel.core.InputStreamDataPart11val data = InputStreamDataPart(ByteArrayInputStream("This is some data".toByteArray()), "data.txt", "text/plain")12val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.response()13import com.github.kittinunf.fuel.core.DataPart14val data = DataPart("This is some data", "data.txt", "text/plain")15val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.response()16import com.github.kittinunf.fuel.core.StringDataPart17val data = StringDataPart("This is some data", "data.txt", "text/plain")18val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.response()19import com.github.kittinunf.fuel.core.StringDataPart
InlineDataPart
Using AI Code Generation
1val dataPart = InlineDataPart("content".toByteArray(), "text/plain")2 .add(dataPart)3 .response()4val dataPart = FileDataPart(File("sample.txt"), "text/plain")5 .add(dataPart)6 .response()7val dataPart = StreamDataPart({ ByteArrayInputStream("content".toByteArray()) }, "text/plain")8 .add(dataPart)9 .response()10val dataPart = ByteArrayDataPart("content".toByteArray(), "text/plain")11 .add(dataPart)12 .response()13val dataPart = InputStreamDataPart({ ByteArrayInputStream("content".toByteArray()) }, "text/plain")14 .add(dataPart)15 .response()16val dataPart = FileDataPart(File("sample.txt"), "text/plain")17 .add(dataPart)18 .response()19val dataPart = StreamDataPart({ ByteArrayInputStream("content".toByteArray()) }, "text/plain")20 .add(dataPart)21 .response()22val dataPart = ByteArrayDataPart("content".toByteArray(), "text/plain")23val (request, response
InlineDataPart
Using AI Code Generation
1val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.responseString()2val (request, response, result) = Fuel.upload("/upload").source { request, url -> file }.responseString()3val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.responseString()4val (request, response, result) = Fuel.upload("/upload").source { request, url -> data }.responseString()5val (request, response, result) = Fuel.upload("/upload").source { request, url -> listOf(data, file, data1, data2) }.responseString()6val file = FileDataPart(File("/path/to/file"), "text
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!!