Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.DownloadRequest.destination
DownLoadAppService.kt
Source:DownLoadAppService.kt
1package com.stxx.wyhvisitorandroid.service2import android.app.Notification3import android.app.NotificationChannel4import android.app.NotificationManager5import android.app.Service6import android.content.Context7import android.content.Intent8import android.content.Intent.FLAG_ACTIVITY_NEW_TASK9import android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION10import android.net.*11import android.os.Build12import android.os.Environment.DIRECTORY_DOWNLOADS13import android.view.WindowManager14import android.widget.RemoteViews15import androidx.annotation.RequiresApi16import androidx.appcompat.app.AlertDialog17import androidx.core.app.NotificationCompat18import androidx.core.app.NotificationManagerCompat19import androidx.core.content.ContextCompat20import androidx.core.content.FileProvider21import com.gavindon.mvvm_lib.base.MVVMBaseApplication22import com.gavindon.mvvm_lib.net.RxScheduler23import com.gavindon.mvvm_lib.widgets.showToast24import com.github.kittinunf.fuel.Fuel25import com.github.kittinunf.fuel.core.requests.DownloadRequest26import com.github.kittinunf.fuel.core.requests.tryCancel27import com.github.kittinunf.fuel.rx.rxResponse28import com.orhanobut.logger.Logger29import com.stxx.wyhvisitorandroid.NOTIFY_ID_DOWNLOAD30import com.stxx.wyhvisitorandroid.R31import com.stxx.wyhvisitorandroid.fileProviderAuth32import io.reactivex.disposables.CompositeDisposable33import org.jetbrains.anko.runOnUiThread34import java.io.File35import kotlin.math.ceil36/**37 * description:ä¸è½½arç§æ®App38 * Created by liNan on 2020/7/8 08:4939 */40class DownLoadAppService : Service() {41 companion object {42 const val REQUEST_CANCEL = "request_cancel"43 }44 private lateinit var downloadFile: File45 private lateinit var downloadRequest: DownloadRequest46 //å建notificationåå¨8.0ä¹ä¸å建NotificationChannel使ç¨47 private val channelId = "com.stxx.wyh.download"48 private var dialogMessage = "æ¯å¦è¦ä¸è½½ARç§æ®apk?"49 //ä¸è½½å®ææ å¿50 private var downloadFinishFlag: Boolean? = null51 private val compositeDisposable = CompositeDisposable()52 private val connectivityManager: ConnectivityManager by lazy {53 getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager54 }55 private var networkCallback: ConnectivityManager.NetworkCallback? = null56 //å建éç¥æ ä¸è½½è¿åº¦æ ·å¼(æ ¹å¸å±åªè½ä½¿ç¨frameLayout linearLayout relativeLayout)57 private val customRemoteViews: RemoteViews by lazy {58 RemoteViews(59 MVVMBaseApplication.appContext.packageName,60 R.layout.notify_download_app61 )62 }63 private val notification: Notification by lazy {64 NotificationCompat.Builder(this, channelId)65 .setTicker("æ£å¨ä¸è½½ARç§æ®apk..", customRemoteViews)66 .setWhen(System.currentTimeMillis())67 .setSmallIcon(R.mipmap.ic_icon)68 .setStyle(NotificationCompat.DecoratedCustomViewStyle())69 .setCustomContentView(customRemoteViews)70 .setAutoCancel(true)71 .setOngoing(true)72 .setOnlyAlertOnce(true)73 .build()74 }75 private val notifyManager by lazy {76 NotificationManagerCompat.from(MVVMBaseApplication.appContext)77 }78 override fun onCreate() {79 super.onCreate()80 network()81 downloadFile = File(this.getExternalFilesDir(DIRECTORY_DOWNLOADS), "ar.apk")82 }83 private fun showDialog() {84 val builder =85 AlertDialog.Builder(MVVMBaseApplication.getCurActivity()!!, R.style.downloadDialog)86 .setTitle("ä¸è½½")87 .setMessage(dialogMessage)88 .setPositiveButton(R.string.confirm) { dialog, _ ->89 downLoadApp()90 showNotify()91 dialog.dismiss()92 }.setNegativeButton("åæ¶") { dialog, which ->93 dialog.dismiss()94 }95 val dialog = builder.create()96 /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {97 dialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)98 } else {99 dialog.window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)100 }*/101 dialog.setOnShowListener { dialogs ->102 val negativeButton =103 (dialogs as AlertDialog).getButton(AlertDialog.BUTTON_NEGATIVE)104 negativeButton.setTextColor(ContextCompat.getColor(this, R.color.light))105 }106 dialog.show()107 }108 override fun onBind(intent: Intent?) = null109 override fun onStartCommand(intent: Intent?, flags: Int, tartId: Int): Int {110 /**111 * 1.å¤ææ¯å¦å·²ç»æä¸è½½å¥½çapk112 * 2.å¤ææ¯å¦æ£å¨ä¸è½½113 */114 if (downloadFile.exists() && downloadFile.length() >= 36000000) {115 Logger.i("${downloadFile.length()}")116 installApp()117 } else {118 if (::downloadRequest.isInitialized) {119 if (downloadFinishFlag == true) {120 showDialog()121 } else {122 MVVMBaseApplication.appContext.showToast("æ£å¨ä¸è½½..")123 }124 } else {125 showDialog()126 }127 }128 return START_NOT_STICKY129 }130 private var lastUpdate = 0L131 private fun downLoadApp() {132 downloadRequest =133 Fuel.download("http://manage.wenyuriverpark.com:8082/apk/ar.apk")134 // æ建FileOutputStream对象,æ件ä¸åå¨ä¼èªå¨æ°å»º135 compositeDisposable.add(downloadRequest.fileDestination { _, _ ->136 downloadFile137 }.progress { readBytes, totalBytes ->138 if (totalBytes != -1L) {139 // allow 2 updates/second max - more than 10/second will be blocked140 if (System.currentTimeMillis() - lastUpdate > 600) {141 lastUpdate = System.currentTimeMillis()142 Logger.i("$readBytes/$totalBytes")143 val progress = readBytes.toFloat() / totalBytes.toFloat() * 100144 updateProgress(progress)145 downloadFinishFlag = false146 }147 } else {148 //æ件é误149 runOnUiThread {150 MVVMBaseApplication.appContext.showToast("æä»¶ç ´æï¼ï¼")151 }152 downloadFinishFlag = true153 }154 }.rxResponse()155 .compose(RxScheduler.applySingleScheduler())156 .subscribe({157 notifyManager.cancel(NOTIFY_ID_DOWNLOAD)158 installApp()159 downloadFinishFlag = true160 }, {161 Logger.i(it.message.toString())162 downloadFinishFlag = false163 })164 )165 }166 private fun updateProgress(progress: Float) {167 customRemoteViews.setProgressBar(168 R.id.notify_progress,169 100,170 ceil(progress).toInt(),171 false172 )173 customRemoteViews.setTextViewText(174 R.id.tvProgress,175 "${ceil(progress).toInt()}%"176 )177 notifyManager.notify(NOTIFY_ID_DOWNLOAD, notification)178 }179 private fun installApp() {180 if (downloadFile.isFile) {181 // éè¿Intentå®è£
APKæ件182 val intents = Intent(Intent.ACTION_INSTALL_PACKAGE)183 val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {184 intents.addFlags(FLAG_GRANT_READ_URI_PERMISSION)185 FileProvider.getUriForFile(this, fileProviderAuth, downloadFile)186 } else {187 Uri.fromFile(downloadFile)188 }189 grantUriPermission(packageName, uri, FLAG_GRANT_READ_URI_PERMISSION)190 intents.addFlags(FLAG_ACTIVITY_NEW_TASK)191 intents.setDataAndType(uri, "application/vnd.android.package-archive")192 startActivity(intents)193 }194 }195 private fun showNotify() {196 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {197 val notificationChannel =198 NotificationChannel(199 channelId,200 "download",201 NotificationManager.IMPORTANCE_DEFAULT202 )203 notifyManager.createNotificationChannel(notificationChannel)204 }205 notifyManager.notify(NOTIFY_ID_DOWNLOAD, notification)206 }207 private fun network() {208 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {209 networkCallback = object : ConnectivityManager.NetworkCallback() {210 override fun onCapabilitiesChanged(211 network: Network?,212 networkCapabilities: NetworkCapabilities213 ) {214 //å½ç½ç»æ¹åæ¶215 notifyManager.cancel(NOTIFY_ID_DOWNLOAD)216 if (::downloadRequest.isInitialized) {217 downloadRequest.tryCancel()218 }219 downloadFinishFlag = true220 network(networkCapabilities)221 }222 }223 connectivityManager.registerNetworkCallback(224 NetworkRequest.Builder().build(),225 networkCallback226 )227 val networkCapabilities =228 connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)229 network(networkCapabilities)230 }231 }232 @RequiresApi(Build.VERSION_CODES.M)233 private fun network(networkCapabilities: NetworkCapabilities) {234 val hasWifi =235 networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)236 val hasCellular =237 networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)238 //æ¥çæ¯å¦æç½(å¿
é¡»æwifiè¿æ¥æè
移å¨ç½ç»å¦åä¼æåºå¼å¸¸)239 val isValidated =240 networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)241 dialogMessage = if (hasWifi) {242 if (isValidated) {243 "æ¨å½åå¤äºWIFIç¶æä¸\næ¯å¦è¦ä¸è½½ARç§æ®apk?"244 } else {245 "æ¨å½åç½ç»ä¸å¯ç¨!\n请è¿æ¥ç½ç»ä¹åå¯ç»§ç»ä¸è½½ARç§æ®apk"246 }247 } else if (hasCellular) {248 if (isValidated) {249 "æ¨å½åæªè¿æ¥WIFI\næ¯å¦è¦ä¸è½½ARç§æ®apk?"250 } else {251 "æ¨å½åç½ç»ä¸å¯ç¨!\n请è¿æ¥ç½ç»ä¹åå¯ç»§ç»ä¸è½½ARç§æ®apk"252 }253 } else {254 "æ¨å½åç½ç»ä¸å¯ç¨!\n请è¿æ¥ç½ç»ä¹åå¯ç»§ç»ä¸è½½ARç§æ®apk"255 }256 }257 override fun onDestroy() {258 notifyManager.cancel(NOTIFY_ID_DOWNLOAD)259 compositeDisposable.clear()260 if (networkCallback != null) {261 connectivityManager.unregisterNetworkCallback(networkCallback)262 }263 stopSelf()264 }265}...
Extensions.kt
Source:Extensions.kt
1package org.imperial.mrc.hint2import com.fasterxml.jackson.databind.JsonNode3import com.fasterxml.jackson.databind.ObjectMapper4import com.github.kittinunf.fuel.core.Headers5import com.github.kittinunf.fuel.core.Parameters6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.core.requests.DownloadRequest9import org.apache.commons.logging.LogFactory10import org.apache.commons.logging.Log11import org.imperial.mrc.hint.exceptions.HintExceptionHandler12import org.imperial.mrc.hint.models.ErrorDetail13import org.imperial.mrc.hint.models.SuccessResponse14import org.imperial.mrc.hint.models.asResponseEntity15import org.springframework.http.HttpStatus16import org.springframework.http.MediaType17import org.springframework.http.ResponseEntity18import org.springframework.util.LinkedMultiValueMap19import org.springframework.util.MultiValueMap20import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody21import java.io.*22import java.security.DigestInputStream23import java.security.MessageDigest24import javax.xml.bind.DatatypeConverter25fun httpStatusFromCode(code: Int): HttpStatus26{27 val status = HttpStatus.resolve(code) ?: return HttpStatus.INTERNAL_SERVER_ERROR28 return if (status <= HttpStatus.NOT_FOUND)29 {30 status31 }32 else33 {34 HttpStatus.INTERNAL_SERVER_ERROR35 }36}37fun headersToMultiMap(headers: Headers): MultiValueMap<String, String>38{39 val result = LinkedMultiValueMap<String, String>()40 headers.entries.forEach {41 result.addAll(it.key, it.value.toList())42 }43 return result44}45@Suppress("UNCHECKED_CAST")46fun Response.asResponseEntity(logger: Log = LogFactory.getLog(HintExceptionHandler::class.java)): ResponseEntity<String>47{48 val httpStatus = httpStatusFromCode(this.statusCode)49 if (this.statusCode == -1)50 {51 return ErrorDetail(httpStatus, "No response returned. The request may have timed out.")52 .toResponseEntity<String>()53 }54 return try55 {56 val body = this.body().asString(MediaType.APPLICATION_JSON_UTF8_VALUE)57 val json = ObjectMapper().readTree(body)58 if (!json.has("status") && !json.has("success"))59 {60 if (!httpStatus.isError)61 {62 SuccessResponse(json).asResponseEntity()63 }64 else65 {66 val message = json.asText()67 logger.error(message)68 ErrorDetail(httpStatus, message).toResponseEntity<String>()69 }70 }71 else if (json.has("status"))72 {73 // this is a hintr response, so already conforms to our response schema74 ResponseEntity.status(httpStatus)75 .contentType(MediaType.APPLICATION_JSON)76 .body(body)77 }78 else79 {80 // this is an ADR response, so convert to our response schema81 formatADRResponse(json, logger)82 }83 }84 catch (e: IOException)85 {86 if (this.body().asString(null).contains("504 Gateway Time-out"))87 {88 //Special case of ADR Gateway Timeouts returning HTML responses which cannot be parsed as JSON89 val message = "ADR request timed out"90 logger.error(message)91 ErrorDetail(HttpStatus.GATEWAY_TIMEOUT, message)92 .toResponseEntity<String>()93 }94 else95 {96 logger.error(e.message)97 ErrorDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Could not parse response.")98 .toResponseEntity<String>()99 }100 }101}102@Suppress("UNCHECKED_CAST")103fun formatADRResponse(json: JsonNode, logger: Log): ResponseEntity<String>104{105 logger.info("Parsing ADR response")106 return if (json["success"].asBoolean())107 {108 logger.info("ADR request successful")109 SuccessResponse(json["result"])110 .asResponseEntity()111 }112 else113 {114 logger.error(json)115 // ckan API always returns a 200, even when the request errors,116 // so just return a 500 for every error response117 ErrorDetail(HttpStatus.INTERNAL_SERVER_ERROR,118 json["error"]["message"].asText(),119 "ADR_ERROR")120 .toResponseEntity<String>()121 }122}123fun Request.getStreamingResponseEntity(headRequest: (url: String, parameters: Parameters?) -> Request)124 : ResponseEntity<StreamingResponseBody>125{126 val responseBody = StreamingResponseBody { outputStream: OutputStream ->127 //return an empty input stream to the body - don't need to re-use it128 val returnEmptyInputStream: () -> InputStream = { ByteArrayInputStream(ByteArray(0)) }129 (this as DownloadRequest).streamDestination { _, _ -> Pair(outputStream, returnEmptyInputStream) }130 .response()131 }132 val headReq = headRequest(this.url.toString(), null)133 val response = headReq.response()134 .second135 val httpStatus = httpStatusFromCode(response.statusCode)136 val headers = headersToMultiMap(response.headers)137 return ResponseEntity(responseBody, headers, httpStatus)138}139fun File.md5sum(): String140{141 val md = MessageDigest.getInstance("MD5")142 FileInputStream(this).use { fis ->143 DigestInputStream(fis, md).use { dis ->144 dis.readBytes()145 }146 }147 return DatatypeConverter.printHexBinary(md.digest())148}...
DownloadRequest.kt
Source:DownloadRequest.kt
...14typealias DestinationAsStreamCallback = () -> InputStream15class DownloadRequest private constructor(private val wrapped: Request) : Request by wrapped {16 override val request: DownloadRequest = this17 override fun toString() = "Download[\n\r\t$wrapped\n\r]"18 private lateinit var destinationCallback: StreamDestinationCallback19 init {20 executionOptions += this::transformResponse21 }22 @Deprecated("Use fileDestination with (Request, Response) -> File")23 fun destination(destination: LegacyDestinationCallback) =24 fileDestination { response: Response, request: Request -> destination(response, request.url) }25 /**26 * Set the destination callback27 *28 * @note destination *MUST* be writable or this may or may not silently fail, dependent on the JVM/engine this is29 * called on. For example, Android silently fails and hangs if used an inaccessible temporary directory, which30 * is syntactically valid.31 *32 * @param destination [FileDestinationCallback] callback called with the [Response] and [Request]33 * @return [DownloadRequest] self34 */35 fun fileDestination(destination: FileDestinationCallback) =36 streamDestination { response: Response, request: Request ->37 destination(response, request).let { file -> Pair(FileOutputStream(file), { FileInputStream(file) }) }38 }39 /**40 * Set the destination callback41 *42 * @note with the current implementation, the stream will be CLOSED after the body has been written to it.43 *44 * @param destination [StreamDestinationCallback] callback called with the [Response] and [Request]45 * @return []46 */47 fun streamDestination(destination: StreamDestinationCallback): DownloadRequest {48 destinationCallback = destination49 return request50 }51 fun progress(progress: ProgressCallback) = responseProgress(progress)52 private fun transformResponse(request: Request, response: Response): Response {53 val (output, inputCallback) = this.destinationCallback(response, request)54 output.use { outputStream ->55 response.body.toStream().use { inputStream ->56 inputStream.copyTo(out = outputStream)57 }58 }59 // This allows the stream to be written to disk first and then return the written file.60 // We can not calculate the length here because inputCallback might not return the actual output as we write it.61 return response.copy(body = DefaultBody.from(inputCallback, null))62 }63 companion object {64 val FEATURE: String = DownloadRequest::class.java.canonicalName65 fun enableFor(request: Request) = request.enabledFeatures66 .getOrPut(FEATURE) { DownloadRequest(request) } as DownloadRequest67 }...
main.kt
Source:main.kt
1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.fuel.core.requests.DownloadRequest3import io.github.typosquat_pd.*4import java.io.File5fun main(args: Array<String>) {6 download_and_expand("https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip")7 val lic = LibrariesIoClient()8 val download_list = lic.search_packages("grant")?.forEach {9 if(it.language == "Java") {10 // Case: Binary11 // TODO12 // - Download .jar13 // - unzip .jar14 // - find .class files15 // - javap -v target.class ( create disassembly file )16 // - extract comment out ( comment out is original code extracted by the assembler )17 // - extract URL & high entropy (obfuscation) string18 } else if(it.language == "python" || it.language == "PHP") {19 // Memo: In the case of Python & PHP, "LibrariesIO" may not provide a Download Url.20 // The Script language allows for easy string checking.21 // TODO ...22 } else if(it.language == "go") {23 // Memo: In the case of GO, "LibrariesIO" may not provide a Download Url.24 // TODO ...25 } else if(it.language == "ruby") {26 // TODO27 // - download gem file (from url)28 // - tar xvf {targetfile}.gem -C {unzip target directory}29 // - unzip "data.tar.gz"30 // - (The Script language allows for easy string checking.)31 } else if(it.language == "npm" || it.language == "typescript") {32 val splittedUrl = it.latest_download_url.split("/")33 val fileName = splittedUrl.get(splittedUrl.size)34 val dr: DownloadRequest = Fuel.download(it.latest_download_url)35 // TODO36 // - download library tgz file (from url)37 // - unzip "target-library.tgz"38 // - search `.js`, `.ts` files39 // - (The Script language allows for easy string checking.)40 } else if(it.language == "c#") {41 // TODO42 // - download nupkg file43 // - rename & unzip nupkg44 // - analyze binary file...?45 }46 }47}48// TODO Rename49fun download_and_expand(url: String) {50 print("start------------")51 val DOWNLOAD_DESTINATION = "/tmp/"52 val splittedUrl = url.split("/")53 val fullFileName = splittedUrl.get(splittedUrl.size - 1)54 val fileAndExtension = fullFileName.split(".", limit=2)55 val fileName = fileAndExtension[0]56 val fileExtension = fileAndExtension[1]57 Fuel.download(url).fileDestination { response, _ ->58// File( DOWNLOAD_DESTINATION, fullFileName)59 File.createTempFile(fileName, fileExtension)60 }61 val downloadedFilePath = DOWNLOAD_DESTINATION + fullFileName62 print("end ------------")63 print(downloadedFilePath)64 print("end ------------")65}...
destination
Using AI Code Generation
1val file = File.createTempFile("download", "tmp")2file.deleteOnExit()3}4File.createTempFile("download", "tmp")5}6File.createTempFile("download", "tmp").absolutePath7}8println("readBytes: $readBytes, totalBytes: $totalBytes")9}10println("readBytes: $readBytes, totalBytes: $totalBytes")11}12println("readBytes: $readBytes, totalBytes: $totalBytes")13}14println("readBytes: $readBytes, totalBytes: $totalBytes")15}
destination
Using AI Code Generation
1downloadRequest.destination { response, url ->2val file = File.createTempFile("download", ".bin")3file.deleteOnExit()4}5downloadRequest.progress { readBytes, totalBytes ->6println("Downloaded $readBytes / $totalBytes bytes.")7}8downloadRequest.response { request, response, result ->9val (data, error) = result10if (data != null) {11println("Download was successful.")12} else {13println("Download failed: ${error.message}")14}15}16downloadRequest.responseString { request, response, result ->17val (data, error) = result18if (data != null) {19println("Download was successful.")20} else {21println("Download failed: ${error.message}")22}23}24downloadRequest.responseJson { request, response, result ->25val (data, error) = result26if (data != null) {27println("Download was successful.")28} else {29println("Download failed: ${error.message}")30}31}32downloadRequest.responseObject { request, response, result ->33val (data, error) = result34if (data != null) {35println("Download was successful.")36} else {37println("Download failed: ${error.message}")38}39}40downloadRequest.responseString { request, response, result ->41val (data, error) = result42if (data != null) {43println("Download was successful.")44} else {45println("Download failed: ${error.message}")46}47}48downloadRequest.response { request, response, result ->49val (data, error) = result50if (
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!!