Best Fuel code snippet using com.github.kittinunf.fuel.Fuel.String.httpDownload
MainActivity.kt
Source:MainActivity.kt
1package com.example.fuel2import android.os.Bundle3import android.os.Handler4import android.util.Log5import androidx.appcompat.app.AppCompatActivity6import com.github.kittinunf.fuel.Fuel7import com.github.kittinunf.fuel.core.Method8import com.github.kittinunf.fuel.core.FuelError9import com.github.kittinunf.fuel.core.FileDataPart10import com.github.kittinunf.fuel.core.FuelManager11import com.github.kittinunf.fuel.core.ResponseDeserializable12import com.github.kittinunf.fuel.core.extensions.authentication13import com.github.kittinunf.fuel.core.extensions.cUrlString14import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult15import com.github.kittinunf.fuel.gson.responseObject16import com.github.kittinunf.fuel.httpDelete17import com.github.kittinunf.fuel.httpGet18import com.github.kittinunf.fuel.httpPost19import com.github.kittinunf.fuel.httpPut20import com.github.kittinunf.fuel.livedata.liveDataObject21import com.github.kittinunf.fuel.rx.rxObject22import com.github.kittinunf.fuel.stetho.StethoHook23import com.github.kittinunf.result.Result24import com.google.gson.Gson25import com.google.gson.reflect.TypeToken26import io.reactivex.android.schedulers.AndroidSchedulers27import io.reactivex.disposables.CompositeDisposable28import io.reactivex.schedulers.Schedulers29import kotlinx.android.synthetic.main.activity_main.mainAuxText30import kotlinx.android.synthetic.main.activity_main.mainClearButton31import kotlinx.android.synthetic.main.activity_main.mainGoButton32import kotlinx.android.synthetic.main.activity_main.mainGoCoroutineButton33import kotlinx.android.synthetic.main.activity_main.mainResultText34import kotlinx.coroutines.CoroutineStart35import kotlinx.coroutines.Dispatchers36import kotlinx.coroutines.GlobalScope37import kotlinx.coroutines.launch38import java.io.File39import java.io.Reader40class MainActivity : AppCompatActivity() {41 private val TAG = MainActivity::class.java.simpleName42 private val bag by lazy { CompositeDisposable() }43 override fun onCreate(savedInstanceState: Bundle?) {44 super.onCreate(savedInstanceState)45 setContentView(R.layout.activity_main)46 FuelManager.instance.apply {47 basePath = "http://httpbin.org"48 baseHeaders = mapOf("Device" to "Android")49 baseParams = listOf("key" to "value")50 hook = StethoHook("Fuel Sample App")51// addResponseInterceptor { loggingResponseInterceptor() }52 }53 mainGoCoroutineButton.setOnClickListener {54 GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT) {55 executeCoroutine()56 }57 }58 mainGoButton.setOnClickListener {59 execute()60 }61 mainClearButton.setOnClickListener {62 mainResultText.text = ""63 mainAuxText.text = ""64 }65 }66 override fun onDestroy() {67 super.onDestroy()68 bag.clear()69 }70 private fun execute() {71 httpGet()72 httpPut()73 httpPost()74 httpPatch()75 httpDelete()76 httpDownload()77 httpUpload()78 httpBasicAuthentication()79 httpListResponseObject()80 httpResponseObject()81 httpGsonResponseObject()82 httpCancel()83 httpRxSupport()84 httpLiveDataSupport()85 }86 private suspend fun executeCoroutine() {87 httpGetCoroutine()88 }89 private suspend fun httpGetCoroutine() {90 val (request, response, result) = Fuel.get("/get", listOf("userId" to "123")).awaitStringResponseResult()91 Log.d(TAG, response.toString())92 Log.d(TAG, request.toString())93 update(result)94 }95 private fun httpCancel() {96 val request = Fuel.get("/delay/10")97 .interrupt { Log.d(TAG, it.url.toString() + " is interrupted") }98 .responseString { _, _, _ -> /* noop */ }99 Handler().postDelayed({ request.cancel() }, 1000)100 }101 private fun httpResponseObject() {102 "https://api.github.com/repos/kittinunf/Fuel/issues/1"103 .httpGet()104 .also { Log.d(TAG, it.cUrlString()) }105 .responseObject(Issue.Deserializer()) { _, _, result -> update(result) }106 }107 private fun httpListResponseObject() {108 "https://api.github.com/repos/kittinunf/Fuel/issues"109 .httpGet()110 .also { Log.d(TAG, it.cUrlString()) }111 .responseObject(Issue.ListDeserializer()) { _, _, result -> update(result) }112 }113 private fun httpGsonResponseObject() {114 "https://api.github.com/repos/kittinunf/Fuel/issues/1"115 .httpGet()116 .also { Log.d(TAG, it.cUrlString()) }117 .responseObject<Issue> { _, _, result -> update(result) }118 }119 private fun httpGet() {120 Fuel.get("/get", listOf("foo" to "foo", "bar" to "bar"))121 .also { Log.d(TAG, it.cUrlString()) }122 .responseString { _, _, result -> update(result) }123 "/get"124 .httpGet()125 .also { Log.d(TAG, it.cUrlString()) }126 .responseString { _, _, result -> update(result) }127 }128 private fun httpPut() {129 Fuel.put("/put", listOf("foo" to "foo", "bar" to "bar"))130 .also { Log.d(TAG, it.cUrlString()) }131 .responseString { _, _, result -> update(result) }132 "/put"133 .httpPut(listOf("foo" to "foo", "bar" to "bar"))134 .also { Log.d(TAG, it.cUrlString()) }135 .responseString { _, _, result -> update(result) }136 }137 private fun httpPost() {138 Fuel.post("/post", listOf("foo" to "foo", "bar" to "bar"))139 .also { Log.d(TAG, it.cUrlString()) }140 .responseString { _, _, result -> update(result) }141 "/post"142 .httpPost(listOf("foo" to "foo", "bar" to "bar"))143 .also { Log.d(TAG, it.cUrlString()) }144 .responseString { _, _, result -> update(result) }145 }146 private fun httpPatch() {147 val manager = FuelManager().apply {148 basePath = "http://httpbin.org"149 baseHeaders = mapOf("Device" to "Android")150 baseParams = listOf("key" to "value")151 }152 manager.forceMethods = true153 manager.request(Method.PATCH, "/patch", listOf("foo" to "foo", "bar" to "bar"))154 .also { Log.d(TAG, it.cUrlString()) }155 .responseString { _, _, result -> update(result) }156 }157 private fun httpDelete() {158 Fuel.delete("/delete", listOf("foo" to "foo", "bar" to "bar"))159 .also { Log.d(TAG, it.cUrlString()) }160 .responseString { _, _, result -> update(result) }161 "/delete"162 .httpDelete(listOf("foo" to "foo", "bar" to "bar"))163 .also { Log.d(TAG, it.cUrlString()) }164 .responseString { _, _, result -> update(result) }165 }166 private fun httpDownload() {167 val n = 100168 Fuel.download("/bytes/${1024 * n}")169 .fileDestination { _, _ -> File(filesDir, "test.tmp") }170 .progress { readBytes, totalBytes ->171 val progress = "$readBytes / $totalBytes"172 runOnUiThread { mainAuxText.text = progress }173 Log.v(TAG, progress)174 }175 .also { Log.d(TAG, it.toString()) }176 .responseString { _, _, result -> update(result) }177 }178 private fun httpUpload() {179 Fuel.upload("/post")180 .add {181 // create random file with some non-sense string182 val file = File(filesDir, "out.tmp")183 file.writer().use { writer ->184 repeat(100) {185 writer.appendln("abcdefghijklmnopqrstuvwxyz")186 }187 }188 FileDataPart(file)189 }190 .progress { writtenBytes, totalBytes ->191 Log.v(TAG, "Upload: ${writtenBytes.toFloat() / totalBytes.toFloat()}")192 }193 .also { Log.d(TAG, it.toString()) }194 .responseString { _, _, result -> update(result) }195 }196 private fun httpBasicAuthentication() {197 val username = "U$3|2|\\|@me"198 val password = "P@$\$vv0|2|)"199 Fuel.get("/basic-auth/$username/$password")200 .authentication()201 .basic(username, password)202 .also { Log.d(TAG, it.cUrlString()) }203 .responseString { _, _, result -> update(result) }204 "/basic-auth/$username/$password".httpGet()205 .authentication()206 .basic(username, password)207 .also { Log.d(TAG, it.cUrlString()) }208 .responseString { _, _, result -> update(result) }209 }210 private fun httpRxSupport() {211 val disposable = "https://api.github.com/repos/kittinunf/Fuel/issues/1"212 .httpGet()213 .rxObject(Issue.Deserializer())214 .subscribeOn(Schedulers.newThread())215 .observeOn(AndroidSchedulers.mainThread())216 .subscribe { result -> Log.d(TAG, result.toString()) }217 bag.add(disposable)218 }219 private fun httpLiveDataSupport() {220 "https://api.github.com/repos/kittinunf/Fuel/issues/1"221 .httpGet()222 .liveDataObject(Issue.Deserializer())223 .observeForever { result -> Log.d(TAG, result.toString()) }224 }225 private fun <T : Any> update(result: Result<T, FuelError>) {226 result.fold(success = {227 mainResultText.append(it.toString())228 }, failure = {229 mainResultText.append(String(it.errorData))230 })231 }232 data class Issue(233 val id: Int = 0,234 val title: String = "",235 val url: String = ""236 ) {237 class Deserializer : ResponseDeserializable<Issue> {238 override fun deserialize(reader: Reader) = Gson().fromJson(reader, Issue::class.java)!!239 }240 class ListDeserializer : ResponseDeserializable<List<Issue>> {241 override fun deserialize(reader: Reader): List<Issue> {242 val type = object : TypeToken<List<Issue>>() {}.type243 return Gson().fromJson(reader, type)244 }245 }246 }247}...
RequestStringExtensionTest.kt
Source:RequestStringExtensionTest.kt
1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.Response7import org.hamcrest.CoreMatchers.notNullValue8import org.hamcrest.CoreMatchers.nullValue9import org.junit.Assert.assertThat10import org.junit.Test11import java.io.File12import java.net.HttpURLConnection13import org.hamcrest.CoreMatchers.`is` as isEqualTo14class RequestStringExtensionTest : BaseTestCase() {15 init {16 FuelManager.instance.basePath = "https://httpbin.org"17 FuelManager.instance.baseHeaders = mapOf("foo" to "bar")18 FuelManager.instance.baseParams = listOf("key" to "value")19 }20 @Test21 fun httpGet() {22 var request: Request? = null23 var response: Response? = null24 var data: Any? = null25 var error: FuelError? = null26 "/get".httpGet().responseString { req, res, result ->27 request = req28 response = res29 val (d, err) = result30 data = d31 error = err32 }33 assertThat(request, notNullValue())34 assertThat(response, notNullValue())35 assertThat(error, nullValue())36 assertThat(data, notNullValue())37 val statusCode = HttpURLConnection.HTTP_OK38 assertThat(response?.httpStatusCode, isEqualTo(statusCode))39 }40 @Test41 fun httpPost() {42 var request: Request? = null43 var response: Response? = null44 var data: Any? = null45 var error: FuelError? = null46 "/post".httpPost().responseString { req, res, result ->47 request = req48 response = res49 val (d, err) = result50 data = d51 error = err52 }53 assertThat(request, notNullValue())54 assertThat(response, notNullValue())55 assertThat(error, nullValue())56 assertThat(data, notNullValue())57 val statusCode = HttpURLConnection.HTTP_OK58 assertThat(response?.httpStatusCode, isEqualTo(statusCode))59 }60 @Test61 fun httpPut() {62 var request: Request? = null63 var response: Response? = null64 var data: Any? = null65 var error: FuelError? = null66 "/put".httpPut().responseString { req, res, result ->67 request = req68 response = res69 val (d, err) = result70 data = d71 error = err72 }73 assertThat(request, notNullValue())74 assertThat(response, notNullValue())75 assertThat(error, nullValue())76 assertThat(data, notNullValue())77 val statusCode = HttpURLConnection.HTTP_OK78 assertThat(response?.httpStatusCode, isEqualTo(statusCode))79 }80 @Test81 fun httpPatch() {82 var request: Request? = null83 var response: Response? = null84 var data: Any? = null85 var error: FuelError? = null86 "https://mockbin.org/request".httpPatch().responseString { req, res, result ->87 request = req88 response = res89 val (d, err) = result90 data = d91 error = err92 }93 assertThat(request, notNullValue())94 assertThat(response, notNullValue())95 assertThat(error, nullValue())96 assertThat(data, notNullValue())97 val statusCode = HttpURLConnection.HTTP_OK98 assertThat(response?.httpStatusCode, isEqualTo(statusCode))99 }100 @Test101 fun httpDelete() {102 var request: Request? = null103 var response: Response? = null104 var data: Any? = null105 var error: FuelError? = null106 "/delete".httpDelete().responseString { req, res, result ->107 request = req108 response = res109 val (d, err) = result110 data = d111 error = err112 }113 assertThat(request, notNullValue())114 assertThat(response, notNullValue())115 assertThat(error, nullValue())116 assertThat(data, notNullValue())117 val statusCode = HttpURLConnection.HTTP_OK118 assertThat(response?.httpStatusCode, isEqualTo(statusCode))119 }120 @Test121 fun httpDownload() {122 var request: Request? = null123 var response: Response? = null124 var data: Any? = null125 var error: FuelError? = null126 val numberOfBytes = 32768L127 "/bytes/$numberOfBytes".httpDownload().destination { response, url ->128 val f = File.createTempFile(numberOfBytes.toString(), null)129 println(f.absolutePath)130 f131 }.responseString { req, res, result ->132 request = req133 response = res134 val (d, err) = result135 data = d136 error = err137 }138 assertThat(request, notNullValue())139 assertThat(response, notNullValue())140 assertThat(error, nullValue())141 assertThat(data, notNullValue())142 val statusCode = HttpURLConnection.HTTP_OK143 assertThat(response?.httpStatusCode, isEqualTo(statusCode))144 }145 @Test146 fun httpUploadWithPut() {147 var request: Request? = null148 var response: Response? = null149 var data: Any? = null150 var error: FuelError? = null151 "/put".httpUpload(Method.PUT).source { request, url ->152 val dir = System.getProperty("user.dir")153 val currentDir = File(dir, "src/test/assets")154 File(currentDir, "lorem_ipsum_long.tmp")155 }.responseString { req, res, result ->156 request = req157 response = res158 val (d, err) = result159 data = d160 error = err161 }162 assertThat(request, notNullValue())163 assertThat(response, notNullValue())164 assertThat(error, nullValue())165 assertThat(data, notNullValue())166 val statusCode = HttpURLConnection.HTTP_OK167 assertThat(response?.httpStatusCode, isEqualTo(statusCode))168 }169 @Test170 fun httpUploadWithPost() {171 var request: Request? = null172 var response: Response? = null173 var data: Any? = null174 var error: FuelError? = null175 "/post".httpUpload().source { request, url ->176 val dir = System.getProperty("user.dir")177 val currentDir = File(dir, "src/test/assets")178 File(currentDir, "lorem_ipsum_long.tmp")179 }.responseString { req, res, result ->180 request = req181 response = res182 val (d, err) = result183 data = d184 error = err185 }186 assertThat(request, notNullValue())187 assertThat(response, notNullValue())188 assertThat(error, nullValue())189 assertThat(data, notNullValue())190 val statusCode = HttpURLConnection.HTTP_OK191 assertThat(response?.httpStatusCode, isEqualTo(statusCode))192 }193}...
tasks.kt
Source:tasks.kt
1package me.eater.emo.forge2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.coroutines.awaitByteArrayResponse4import com.github.kittinunf.fuel.coroutines.awaitString5import com.github.kittinunf.fuel.httpDownload6import com.github.kittinunf.fuel.httpGet7import me.eater.emo.EmoContext8import me.eater.emo.Target9import me.eater.emo.VersionSelector10import me.eater.emo.forge.dto.manifest.v1.Library11import me.eater.emo.forge.dto.manifest.v1.Manifest12import me.eater.emo.forge.dto.promotions.Promotions13import me.eater.emo.utils.Process14import me.eater.emo.utils.await15import me.eater.emo.utils.io16import me.eater.emo.utils.parallel17import org.tukaani.xz.XZInputStream18import java.io.File19import java.io.FileOutputStream20import java.nio.file.Files21import java.nio.file.Paths22import java.nio.file.StandardCopyOption23import java.util.jar.JarEntry24import java.util.jar.JarFile25import java.util.jar.JarOutputStream26import java.util.jar.Pack20027/**28 * Process that fetches the known versions of Forge, and if needed selects the correct minecraft version29 */30class FetchForgeVersions : Process<EmoContext> {31 override fun getName() = "forge.fetch_versions"32 override fun getDescription() = "Fetching known Forge versions"33 override suspend fun execute(context: EmoContext) {34 if (context.forgeVersion!!.isStatic()) {35 context.selectedForgeVersion = context.forgeVersion.selector36 return37 }38 val manifest = "https://files.minecraftforge.net/maven/net/minecraftforge/forge/promotions.json"39 .httpGet()40 .awaitString()41 val promotions = Promotions.fromJson(manifest)!!42 val key = when (context.selectedMinecraftVersion) {43 null -> context.forgeVersion.selector44 else -> "${context.selectedMinecraftVersion!!.id}-${context.forgeVersion.selector}"45 }46 if (!promotions.promos.containsKey(key)) {47 throw Error("No forge distribution found for $key")48 }49 promotions.promos.getValue(key).run {50 context.selectedForgeVersion = version51 context.minecraftVersion = VersionSelector(minecraftVersion)52 }53 }54}55/**56 * Process that fetches the universal Forge jar57 */58class FetchUniversal : Process<EmoContext> {59 override fun getName() = "forge.v1.fetch_universal"60 override fun getDescription() = "Fetch universal Forge runtime"61 override suspend fun execute(context: EmoContext) {62 val versionTuple = "${context.selectedMinecraftVersion!!.id}-${context.selectedForgeVersion!!}"63 val artifactUrl =64 "https://files.minecraftforge.net/maven/net/minecraftforge/forge/$versionTuple/forge-$versionTuple-universal.jar"65 io {66 artifactUrl67 .httpDownload()68 .fileDestination { _, _ -> Paths.get(context.installLocation.toString(), "forge.jar").toFile() }69 .await()70 }71 }72}73/**74 * Process that loads the install manifest from the universal forge jar75 */76class LoadForgeManifest : Process<EmoContext> {77 override fun getName() = "forge.v1.load_manifest"78 override fun getDescription() = "Loading Forge install manifest"79 override suspend fun execute(context: EmoContext) {80 io {81 val jar = JarFile(Paths.get(context.installLocation.toString(), "forge.jar").toFile())82 val json = String(jar.getInputStream(jar.getJarEntry("version.json")).readBytes())83 context.forgeManifest = Manifest.fromJson(json)!!84 jar.close()85 }86 }87}88/**89 * Process that fetches the libraries needed for forge90 */91class FetchForgeLibraries : Process<EmoContext> {92 override fun getName() = "forge.v1.fetch_libraries"93 override fun getDescription() = "Fetching libraries for Forge"94 @ExperimentalUnsignedTypes95 override suspend fun execute(context: EmoContext) {96 parallel((context.forgeManifest!! as Manifest).libraries) {97 if (it.clientreq === null && it.serverreq === null) {98 return@parallel99 }100 val mirror = it.url ?: "https://libraries.minecraft.net"101 val file = Paths.get(context.installLocation.toString(), "libraries", it.getPath())102 Files.createDirectories(file.parent)103 if (Files.exists(file)) return@parallel104 try {105 (mirror + '/' + it.getPath())106 .httpDownload()107 .fileDestination { _, _ -> file.toFile() }108 .await()109 } catch (t: Throwable) {110 if (t is FuelError && t.response.statusCode == 404 && it.url != null) {111 tryDownloadingPack(it, file.toFile())112 } else {113 throw t114 }115 }116 }117 if (context.target == Target.Client) {118 val newPath = Paths.get(119 context.installLocation.toString(),120 "libraries/net/minecraftforge/forge",121 "${context.selectedMinecraftVersion!!.id}-${context.selectedForgeVersion!!}",122 "forge-${context.selectedMinecraftVersion!!.id}-${context.selectedForgeVersion!!}.jar"123 )124 Files.createDirectories(newPath.parent)125 Files.move(126 Paths.get(context.installLocation.toString(), "forge.jar"),127 newPath,128 StandardCopyOption.REPLACE_EXISTING129 )130 }131 }132 @ExperimentalUnsignedTypes133 suspend fun tryDownloadingPack(lib: Library, dest: File) {134 val (_, _, data) = ("${lib.url!!}/${lib.getPath()}.pack.xz")135 .httpGet()136 .awaitByteArrayResponse()137 io {138 val decompressed = XZInputStream(data.inputStream()).readBytes()139 val decompressedLen = decompressed.size140 val blobLen = (decompressed[decompressedLen - 8].toUByte() and 0xFF.toUByte()).toInt() or141 ((decompressed[decompressedLen - 7].toUByte() and 0xFF.toUByte()).toInt() shl 8) or142 ((decompressed[decompressedLen - 6].toUByte() and 0xFF.toUByte()).toInt() shl 16) or143 ((decompressed[decompressedLen - 5].toUByte() and 0xFF.toUByte()).toInt() shl 24)144 val checksums = decompressed.copyOfRange(decompressedLen - blobLen - 8, decompressedLen - 8)145 val jarFile = FileOutputStream(dest)146 val jar = JarOutputStream(jarFile)147 Pack200.newUnpacker().unpack(decompressed.inputStream(0, decompressedLen - blobLen - 8), jar)148 val checksumsEntry = JarEntry("checksums.sha1")149 checksumsEntry.time = 0150 jar.putNextEntry(checksumsEntry)151 jar.write(checksums)152 jar.closeEntry()153 jar.close()154 jarFile.close()155 }156 }157}...
Models.kt
Source:Models.kt
1package com.java.lichenhao2import android.graphics.Bitmap3import android.graphics.BitmapFactory4import android.os.Parcelable5import com.github.kittinunf.fuel.core.FuelError6import com.github.kittinunf.fuel.httpDownload7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.result.Result9import com.github.kittinunf.result.map10import com.github.kittinunf.result.success11import com.google.gson.annotations.SerializedName12import kotlinx.android.parcel.IgnoredOnParcel13import kotlinx.android.parcel.Parcelize14import java.io.File15import java.lang.NullPointerException16// è¿äºdata classé使ç¨List没æä»»ä½ä»·å¼ï¼ç´æ¥ç¨Arrayå³å¯17// è¦åç"建议å®ç°equals/hashCode"ä¸ç¨çï¼æ²¡æå®ç°çç±»é½ä¸ä¼ç¨å°è¿äºæ¹æ³18@Parcelize // è¿ç©æçåè¿ç¨å®å19data class Response(20 val pageSize: Int, //æ°é»æ»é¡µæ°21 val total: Int, //符åæ¡ä»¶çæ°é»æ»æ°22 val `data`: Array<News>,23 val currentPage: Int24) : Parcelable25// æä¹
ä¿åçå
容26@Parcelize27data class NewsExt(28 val news: News,29 var read: Boolean, // 已读30 var favorite: Boolean,31 val imageDataList: Array<ByteArray?>, // ä¸è½½çå¾çå
·ä½å
容ï¼ä¸æ ånews.imageListä¸ä¸å¯¹åº32 var videoPath: String? // ä¸è½½çè§é¢ç´æ¥ä¿åå°æ件ä¸33) : Parcelable {34 constructor(news: News) : this(35 news,36 NewsData.isRead(news),37 NewsData.isFavorite(news),38 arrayOfNulls(news.imageList.size),39 null40 )41 inline fun downloadImage(which: Int, crossinline handler: (Result<Bitmap, FuelError>) -> Unit) {42 imageDataList[which]?.let {43 val bitmap: Bitmap? = BitmapFactory.decodeByteArray(it, 0, it.size)44 if (bitmap != null) {45 handler(Result.success(bitmap))46 } else {47 handler(Result.error(FuelError.wrap(NullPointerException()))) // å¯è½æ¯å¼ gifï¼ä¸æ¯æ48 }49 return50 }51 news.imageList[which].httpGet().response { _, _, result ->52 result.map { BitmapFactory.decodeByteArray(it, 0, it.size) }.apply(handler)53 result.success { imageDataList[which] = it }54 }55 }56 // è°ç¨è
ä¿è¯news.videoé空57 // handlerå¤ççæ¯è§é¢æ件å(å 为è§é¢ææ¾å¨åºä¸æ¥åè§é¢å
容ï¼åªæ¥åurl)58 inline fun downloadVideo(crossinline handler: (String) -> Unit) {59 val video = news.video!!60 val videoPath = videoPath ?: run {61 handler(video) // å¦æ没ææ¬å°ä¸è½½ï¼åç´æ¥ææ¾videoç½å(è¿æ ·ç¨æ·ä¸éè¦çå¾
)62 val path = "${GLOBAL_CONTEXT.filesDir.absolutePath}/video${System.currentTimeMillis()}.mp4"63 video.httpDownload().fileDestination { _, _ -> File(path) }.response { _, _, _ ->64 videoPath = path // ä¸é»å¡ï¼ä¸è½½å¥½æ¶æ设置videoPath65 }66 return67 }68 handler(videoPath) // ææ¬å°ä¸è½½ï¼ææ¾æ件69 }70 override fun equals(other: Any?) = other is NewsExt && news == other.news71 override fun hashCode() = news.hashCode()72}73// imageStringåvideoç"为空"ï¼æ大æ¦çæ¯ç©ºå符串ï¼ä½ä¹æå¯è½æ¯ä¸åå¨74@Parcelize75data class News(76 @SerializedName("image")77 val imageString: String?, //æ°é»æå¾ï¼å¯è½ä¸ºç©º(é空æ¶æ ¼å¼æ¯æ£å¸¸çjsonæ°ç»)78 val publishTime: String, //æ°é»åå¸æ¶é´ï¼é¨åæ°é»ç±äºèªèº«é误å¯è½æ¶é´ä¼å¾å¤§(å¦9102å¹´)79 val keywords: Array<Keyword>, //å
³é®è¯80 val language: String, //æ°é»è¯è¨81 val video: String?, //è§é¢ï¼ä¸è¬ä¸ºç©º82 val title: String, //æ°é»é¢ç®83 val `when`: Array<When>, //æ°é»ä¸ç¸å
³æ¶é´åç¸å
³åº¦84 val content: String, //æ£æ85 val persons: Array<Person>, //æ°é»æå人ç©ï¼æå次æ°åå¨xloreä¸ç¥è¯å¡çurl86 val newsID: String, //æ°é»ID87 val crawlTime: String, //ç¬åæ¶é´88 val organizations: Array<Organization>, //åå¸æ°é»ç»ç»89 val publisher: String, //åºçè
90 val locations: Array<Location>, //æ°é»æåä½ç½®ï¼ä½ç½®ç»çº¬åº¦ï¼æå次æ°91 val `where`: Array<Where>, //æ°é»ç¸å
³ä½ç½®åç¸å
³åº¦92 val category: String, //ç±»å«93 val who: Array<Who> //æ°é»ç¸å
³äººåç¸å
³åº¦94) : Parcelable {95 @IgnoredOnParcel96 private var _imageList: List<String>? = null97 val imageList: List<String>98 get() = _imageList ?: run {99 val tmp = (imageString ?: "")100 .replace("[", "").replace("]", "")101 .split(',')102 .map { it.trim() }103 .filter { it.isNotEmpty() }104 _imageList = tmp105 tmp106 }107 override fun equals(other: Any?) = other is News && newsID == other.newsID108 override fun hashCode() = newsID.hashCode()109}110@Parcelize111data class Keyword(112 val score: Float, //å
³å»ºåº¦113 val word: String //è¯è¯114) : Parcelable115@Parcelize116data class When(117 val score: Float,118 val word: String119) : Parcelable120@Parcelize121data class Person(122 val count: Int,123 val linkedURL: String?,124 val mention: String125) : Parcelable126@Parcelize127data class Organization(128 val count: Int,129 val linkedURL: String?,130 val mention: String131) : Parcelable132@Parcelize133data class Location(134 val count: Int,135 val lat: Float,136 val linkedURL: String?,137 val lng: Float,138 val mention: String139) : Parcelable140@Parcelize141data class Where(142 val score: Float,143 val word: String144) : Parcelable145@Parcelize146data class Who(147 val score: Float,148 val word: String149) : Parcelable...
Files.kt
Source:Files.kt
1package flank.common2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.awaitUnit4import com.github.kittinunf.fuel.httpDownload5import java.io.File6import java.io.IOException7import java.nio.file.Files8import java.nio.file.Path9import java.nio.file.Paths10import java.nio.file.StandardCopyOption11val defaultCredentialPath: Path by lazy {12 Paths.get(userHome, ".config/gcloud/application_default_credentials.json")13}14val userHome: String by lazy {15 if (isWindows) System.getenv("HOMEPATH") else System.getProperty("user.home")16}17val appDataDirectory: String by lazy {18 if (isWindows) System.getenv("APPDATA") else System.getProperty("user.home")19}20val dotFlank = Paths.get(userHome, ".flank")21fun linkFiles(22 link: String,23 target: String24) {25 if (isWindows) createCopy(target, link)26 else createSymbolicLink(link, target)27}28fun createCopy(sourceDirectoryLocation: String, destinationDirectoryLocation: String) {29 if (destinationDirectoryLocation.fileExists()) {30 deleteDirectory(destinationDirectoryLocation)31 }32 copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation)33}34fun createFileCopy(source: String, destination: String): Path =35 Files.copy(Paths.get(source), Paths.get(destination), StandardCopyOption.REPLACE_EXISTING)36fun copyDirectory(sourceDirectoryLocation: String, destinationDirectoryLocation: String) {37 Files.walk(Paths.get(sourceDirectoryLocation))38 .forEach { source: Path ->39 val destination =40 Paths.get(destinationDirectoryLocation, source.toString().substring(sourceDirectoryLocation.length))41 try {42 Files.copy(source, destination)43 } catch (e: IOException) {44 logLn(e.localizedMessage)45 }46 }47}48fun deleteDirectory(directory: String) {49 if (directory.fileExists()) deleteDirectory(directory.toFile())50}51private fun deleteDirectory(directory: File): Boolean {52 val allContents = directory.listFiles()53 if (allContents != null) {54 for (file in allContents) {55 deleteDirectory(file)56 }57 }58 return directory.delete()59}60fun createSymbolicLink(61 link: String,62 target: String63): Path = Files.createSymbolicLink(64 Paths.get(link).also { linkPath -> if (Files.isSymbolicLink(linkPath)) Files.delete(linkPath) }.toAbsolutePath()65 .normalize(),66 Paths.get(target).toAbsolutePath().normalize()67)68fun createLinkToFile(link: Path, target: Path): Path =69 if (isWindows) createFileCopy(target.toString(), link.toString())70 else Files.createSymbolicLink(link, target.fileName)71fun downloadFile(sourceUrl: String, destination: String) {72 Fuel.download(sourceUrl)73 .fileDestination { _, _ -> File(destination) }74 .responseString()75}76suspend fun String.downloadFile(destination: String) = this.httpDownload().fileDestination { _, _ ->77 Files.createFile(Paths.get(destination)).toFile().also {78 logLn("Ktlint written to: ${it.absolutePath}")79 }80}.awaitUnit()81fun downloadFile(sourceUrl: String, destinationPath: Path) {82 Fuel.download(sourceUrl)83 .fileDestination { _, _ -> destinationPath.toFile() }84 .responseString()85}86fun String.toFile(): File = Paths.get(this).toFile()87fun String.deleteFile() = Paths.get(this).delete()88fun createDirectoryIfNotExist(path: Path) {89 if (Files.notExists(path)) Files.createDirectory(path)90}91fun File.hasAllFiles(fileList: List<String>): Boolean {92 val directoryFiles = list() ?: emptyArray()93 return fileList.all { it in directoryFiles }94}95fun String.fileExists(): Boolean = Paths.get(this).exists()96fun osPathSeparator() = (if (isWindows) "\\" else "/")97private fun Path.exists(): Boolean = Files.exists(this)98private fun Path.isFile(): Boolean = !Files.isDirectory(this)99private fun Path.delete(): Boolean {100 return if (isFile() && exists()) {101 Files.delete(this)102 true103 } else {104 false105 }106}...
UpdateUtil.kt
Source:UpdateUtil.kt
1package com.gh0u1l5.wechatmagician.util2import android.app.Activity3import android.content.Context4import android.content.Intent5import android.net.Uri6import android.os.Build7import android.support.v4.content.FileProvider8import android.support.v7.app.AlertDialog9import android.util.Log10import android.webkit.MimeTypeMap11import com.gh0u1l5.wechatmagician.BuildConfig12import com.gh0u1l5.wechatmagician.Global.MAGICIAN_FILE_PROVIDER13import com.gh0u1l5.wechatmagician.R14import com.github.kittinunf.fuel.android.extension.responseJson15import com.github.kittinunf.fuel.httpDownload16import com.github.kittinunf.fuel.httpGet17import com.github.kittinunf.result.Result18import java.io.File19object UpdateUtil {20 private const val TAG = "UpdateUtil"21 private const val UPDATE_SERVER = "http://www.gh0u1l5.me/wechat-magician"22 private const val UPDATE_JSON = "$UPDATE_SERVER/update.json"23 fun checkVersion(activity: Activity) {24// {25// "version_code": 51,26// "address": "./apks/WechatMagician-2.8.1.apk",27// "description": "Test"28// }29 UPDATE_JSON.httpGet().responseJson { _, _, result ->30 if (result is Result.Failure) {31 return@responseJson32 }33 val version = result.get().obj()34 val versionCode = version["version_code"] as Int35 if (versionCode > BuildConfig.VERSION_CODE) {36 val apkAddress = "$UPDATE_SERVER/${version["address"]}"37 val description = version["description"] as String38 requireUpdate(activity, apkAddress, description)39 }40 }41 }42 private fun requireUpdate(activity: Activity, apkAddress: String, description: String) {43 activity.runOnUiThread {44 AlertDialog.Builder(activity)45 .setIcon(R.mipmap.ic_launcher)46 .setTitle(R.string.prompt_update_discovered)47 .setMessage(description)48 .setPositiveButton(R.string.button_update, { dialog, _ ->49 downloadAndInstallApk(activity, apkAddress)50 dialog.dismiss()51 })52 .setNegativeButton(R.string.button_cancel, { dialog, _ ->53 dialog.dismiss()54 })55 .show()56 }57 }58 private fun downloadAndInstallApk(context: Context, apkAddress: String) {59 val apkFile = File.createTempFile("temp", ".apk", context.cacheDir)60 apkAddress.httpDownload().destination { _, _ -> apkFile }.response { _, _, result ->61 if (result is Result.Success) {62 installApk(context, apkFile)63 }64 }65 }66 private fun installApk(context: Context, apk: File) {67 try {68 context.startActivity(Intent().apply {69 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {70 action = Intent.ACTION_INSTALL_PACKAGE71 data = FileProvider.getUriForFile(context, MAGICIAN_FILE_PROVIDER, apk)72 flags = Intent.FLAG_GRANT_READ_URI_PERMISSION73 } else {74 action = Intent.ACTION_VIEW75 data = Uri.fromFile(apk)76 type = MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk")77 flags = Intent.FLAG_ACTIVITY_NEW_TASK78 }79 })80 } catch (t: Throwable) {81 Log.w(TAG, t)82 }83 }84}...
ApiWrapper.kt
Source:ApiWrapper.kt
1package com.github.firenox89.shinobooru.repo2import android.content.Context3import com.github.firenox89.shinobooru.repo.model.Post4import com.github.firenox89.shinobooru.repo.model.Tag5import com.github.kittinunf.fuel.core.FuelError6import com.github.kittinunf.fuel.core.FuelManager7import com.github.kittinunf.fuel.core.ResponseDeserializable8import com.github.kittinunf.fuel.core.awaitResult9import com.github.kittinunf.fuel.coroutines.awaitObjectResult10import com.github.kittinunf.fuel.httpDownload11import com.github.kittinunf.fuel.httpGet12import com.github.kittinunf.result.Result13import com.google.gson.Gson14import timber.log.Timber15import java.io.File16class ApiWrapper(private val appContext: Context) {17 init {18 //TODO: check if internet is available19 //yande.re does not talk to android user agents...20 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Java/1.8.0_112")21 }22 suspend fun requestPost(board: String,23 page: Int,24 tags: String = "",25 limit: Int = 20): Result<List<Post>, FuelError> =26 //TODO: add board dependent request limits, so that we can stop before the board will stop us27 buildPostRequest(board, page, tags, limit).also { Timber.d("request '$it'") }.httpGet().awaitObjectResult(PostDeserializer)28 suspend fun requestTag(board: String, tagName: String): Result<List<Tag>, FuelError> =29 //add protocol if it is missing30 "${board.prepentHttp()}/tag.json?name=$tagName&limit=0".also {31 Timber.i("Request tag info from board '$board' with name '$tagName'. Request '$it'")32 }.httpGet().awaitObjectResult(TagDeserializer).also { Timber.d("Requested Tags $board, $tagName") }33 private fun String.prepentHttp(): String = if (this.startsWith("http")) this else "https://$this"34 private fun buildPostRequest(board: String, page: Int, tags: String, limit: Int): String =35 "${board.prepentHttp()}/post.json?limit=$limit" +36 (if (page > 1) "&page=$page" else "") +37 (if (tags != "") "&tags=$tags" else "")38 suspend fun downloadPost(post: Post, destination: File) =39 post.file_url.httpDownload().fileDestination { _, _ ->40 destination41 }.awaitResult(NoopDeserializer)42 object PostDeserializer : ResponseDeserializable<List<Post>> {43 override fun deserialize(content: String): List<Post> = Gson().fromJson(content, Array<Post>::class.java).toList()44 }45 object TagDeserializer : ResponseDeserializable<List<Tag>> {46 override fun deserialize(content: String): List<Tag> = Gson().fromJson(content, Array<Tag>::class.java).toList()47 }48 object NoopDeserializer : ResponseDeserializable<Unit> {49 override fun deserialize(content: String): Unit = Unit50 }51}...
Fuel.kt
Source:Fuel.kt
1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Parameters5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.RequestFactory7import com.github.kittinunf.fuel.core.requests.DownloadRequest8import com.github.kittinunf.fuel.core.requests.UploadRequest9object Fuel : RequestFactory.Convenience by FuelManager.instance {10 var trace = false11 fun trace(function: () -> String) {12 @Suppress("ConstantConditionIf")13 if (trace) println(function())14 }15 fun reset() = FuelManager.instance.reset()16}17fun String.httpGet(parameters: Parameters? = null): Request =18 Fuel.get(this, parameters)19fun RequestFactory.PathStringConvertible.httpGet(parameter: Parameters? = null): Request =20 this.path.httpGet(parameter)21fun String.httpPost(parameters: Parameters? = null): Request =22 Fuel.post(this, parameters)23fun RequestFactory.PathStringConvertible.httpPost(parameters: Parameters? = null): Request =24 this.path.httpPost(parameters)25fun String.httpPut(parameters: Parameters? = null): Request =26 Fuel.put(this, parameters)27fun RequestFactory.PathStringConvertible.httpPut(parameter: Parameters? = null): Request =28 this.path.httpPut(parameter)29fun String.httpPatch(parameters: Parameters? = null): Request =30 Fuel.patch(this, parameters)31fun RequestFactory.PathStringConvertible.httpPatch(parameter: Parameters? = null): Request =32 this.path.httpPatch(parameter)33fun String.httpDelete(parameters: Parameters? = null): Request =34 Fuel.delete(this, parameters)35fun RequestFactory.PathStringConvertible.httpDelete(parameter: Parameters? = null): Request =36 this.path.httpDelete(parameter)37fun String.httpDownload(parameter: Parameters? = null, method: Method = Method.GET): DownloadRequest =38 Fuel.download(this, method, parameter)39fun RequestFactory.PathStringConvertible.httpDownload(parameters: Parameters? = null, method: Method = Method.GET): DownloadRequest =40 this.path.httpDownload(parameters, method)41fun String.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =42 Fuel.upload(this, method, parameters)43fun RequestFactory.PathStringConvertible.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =44 this.path.httpUpload(parameters, method)45fun String.httpHead(parameters: Parameters? = null): Request =46 Fuel.head(this, parameters)47fun RequestFactory.PathStringConvertible.httpHead(parameters: Parameters? = null): Request =48 this.path.httpHead(parameters)...
String.httpDownload
Using AI Code Generation
1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.result.Result3fun main(args: Array<String>) {4 println("Downloading $url")5 Fuel.get(url).responseString { request, response, result ->6 when (result) {7 is Result.Failure -> {8 println("Error: ${result.getException()}")9 }10 is Result.Success -> {11 println("Got ${result.get().length} bytes")12 }13 }14 }15}16import com.github.kittinunf.fuel.Fuel17import com.github.kittinunf.result.Result18fun main(args: Array<String>) {19 println("Downloading $url")20 Fuel.get(url).responseString { request, response, result ->21 when (result) {22 is Result.Failure -> {23 println("Error: ${result.getException()}")24 }25 is Result.Success -> {26 println("Got ${result.get().length} bytes")27 }28 }29 }30}31import com.github.kittinunf.fuel.Fuel32import com.github.kittinunf.result.Result33fun main(args: Array<String>) {34 println("Downloading $url")35 Fuel.get(url).responseString { request, response, result ->36 when (result) {37 is Result.Failure -> {38 println("Error: ${result.getException()}")39 }40 is Result.Success -> {41 println("Got ${result.get().length} bytes")42 }43 }44 }45}46import com.github.kittinunf.fuel.Fuel47import com.github.kittinunf.result.Result48fun main(args: Array<String>) {49 println("Downloading $url")50 Fuel.get(url).responseString { request, response, result ->51 when (result) {52 is Result.Failure -> {53 println("Error: ${result.getException()}")54 }
String.httpDownload
Using AI Code Generation
1 String fileName = "logo.png";2 String destinationFile = "/tmp/" + fileName;3 String urlWithFileName = url + "/" + fileName;4 File file = new File(destinationFile);5 if (!file.exists()) {6 String result = urlWithFileName.httpDownload().destination { response, url ->7 File.createTempFile("mytempfile", ".tmp")8 }.responseString().second.get()9 println(result)10 }11 import com.github.kittinunf.fuel.Fuel12 import com.github.kittinunf.fuel.core.extensions.authentication13 import com.github.kittinunf.fuel.core.extensions.cUrlString14 import com.github.kittinunf.fuel.core.extensions.responseString15 import com.github.kittinunf.fuel.core.requests.DownloadRequest16 import com.github.kittinunf.fuel.core.requests.Request17 import com.github.kittinunf.fuel.core.requests.cUrlString18 import com.github.kittinunf.fuel.core.requests.responseString19 import com.github.kittinunf.fuel.core.response20 import com.github.kittinunf.fuel.core.responseString21 import com.github.kittinunf.fuel.httpDownload22 import com.github.kittinunf.fuel.httpGet23 import com.github.kittinunf.fuel.httpPost24 import com.github.kittinunf.fuel.httpUpload25 import com.github.kittinunf.fuel.moshi.responseObject26 import com.github.kittinunf.fuel.moshi.responseObject
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!!