How to use DownloadRequest class of com.github.kittinunf.fuel.core.requests package

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.DownloadRequest

FuelManager.kt

Source:FuelManager.kt Github

copy

Full Screen

...3import com.github.kittinunf.fuel.core.RequestFactory.PathStringConvertible4import com.github.kittinunf.fuel.core.RequestFactory.RequestConvertible5import com.github.kittinunf.fuel.core.interceptors.ParameterEncoder6import com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor7import com.github.kittinunf.fuel.core.requests.DownloadRequest8import com.github.kittinunf.fuel.core.requests.UploadRequest9import com.github.kittinunf.fuel.core.requests.download10import com.github.kittinunf.fuel.core.requests.upload11import com.github.kittinunf.fuel.toolbox.HttpClient12import com.github.kittinunf.fuel.util.readWriteLazy13import java.net.Proxy14import java.security.KeyStore15import java.util.concurrent.Executor16import java.util.concurrent.ExecutorService17import java.util.concurrent.Executors18import javax.net.ssl.HostnameVerifier19import javax.net.ssl.HttpsURLConnection20import javax.net.ssl.SSLContext21import javax.net.ssl.SSLSocketFactory22import javax.net.ssl.TrustManagerFactory23typealias FoldableRequestInterceptor = (RequestTransformer) -> RequestTransformer24typealias FoldableResponseInterceptor = (ResponseTransformer) -> ResponseTransformer25class FuelManager : RequestFactory, RequestFactory.Convenience {26 var client: Client by readWriteLazy { HttpClient(proxy, hook = hook) }27 var proxy: Proxy? = null28 var basePath: String? = null29 var timeoutInMillisecond: Int = 15_00030 var timeoutReadInMillisecond: Int = timeoutInMillisecond31 var progressBufferSize: Int = DEFAULT_BUFFER_SIZE32 var hook: Hook = DefaultHook()33 var baseHeaders: Map<String, String>? = null34 var baseParams: Parameters = emptyList()35 var keystore: KeyStore? = null36 var socketFactory: SSLSocketFactory by readWriteLazy {37 keystore?.let {38 val trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())39 trustFactory.init(it)40 val sslContext = SSLContext.getInstance("SSL")41 sslContext.init(null, trustFactory.trustManagers, null)42 sslContext.socketFactory43 } ?: HttpsURLConnection.getDefaultSSLSocketFactory()44 }45 var hostnameVerifier: HostnameVerifier by readWriteLazy {46 HttpsURLConnection.getDefaultHostnameVerifier()47 }48 // background executionOptions49 var executorService: ExecutorService by readWriteLazy {50 Executors.newCachedThreadPool { command ->51 Thread(command).also { thread ->52 thread.priority = Thread.NORM_PRIORITY53 thread.isDaemon = true54 }55 }56 }57 private val requestInterceptors: MutableList<FoldableRequestInterceptor> =58 mutableListOf(ParameterEncoder)59 private val responseInterceptors: MutableList<FoldableResponseInterceptor> =60 mutableListOf(redirectResponseInterceptor(this))61 // callback executionOptions62 var callbackExecutor: Executor by readWriteLazy { createEnvironment().callbackExecutor }63 var forceMethods: Boolean = false64 /**65 * Make a request using [method] to [path] with [parameters]66 *67 * @see FuelManager.instance68 * @see FuelManager.applyOptions69 *70 * @param method [Method] the HTTP method to make the request with71 * @param path [String] the absolute url or relative to [FuelManager.instance] basePath72 * @param parameters [Parameters?] list of parameters73 *74 * @return [Request] the request75 */76 override fun request(method: Method, path: String, parameters: Parameters?): Request {77 val request = request(Encoding(78 httpMethod = method,79 urlString = path,80 baseUrlString = basePath,81 parameters = if (parameters == null) baseParams else baseParams + parameters82 ).request)83 return applyOptions(request)84 }85 /**86 * Make a request using [method] to [convertible]'s path with [parameters]87 *88 * @see FuelManager.instance89 * @see RequestFactory(Method, String, Parameters?)90 *91 * @param method [Method] the HTTP method to make the request with92 * @param convertible [PathStringConvertible]93 * @param parameters [Parameters?] list of parameters94 *95 * @return [Request] the request96 */97 override fun request(method: Method, convertible: PathStringConvertible, parameters: Parameters?): Request =98 request(method, convertible.path, parameters)99 /**100 * Make a request using from [convertible]101 *102 * @param convertible [RequestConvertible] the instance that can be turned into a [Request]103 * @return [Request] the request104 */105 override fun request(convertible: RequestConvertible): Request = applyOptions(convertible.request)106 /**107 * Create a [method] [Request] to [path] with [parameters], which can download to a file108 *109 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path110 * @param method [Method] the method to download with, defaults to [Method.GET]111 * @param parameters [Parameters] the optional parameters112 * @return [DownloadRequest] the request (extended for download)113 */114 override fun download(path: String, method: Method, parameters: Parameters?): DownloadRequest {115 val request = Encoding(116 httpMethod = method,117 urlString = path,118 baseUrlString = basePath,119 parameters = if (parameters == null) baseParams else baseParams + parameters120 ).request121 return applyOptions(request).download()122 }123 /**124 * Create a [method] [Request] to [path] with [parameters], which can upload blobs and Data Parts125 *126 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path127 * @param method [Method] the method to upload with, defaults to [Method.POST]128 * @param parameters [Parameters] the optional parameters129 * @return [UploadRequest] the request (extended for upload)130 */131 override fun upload(path: String, method: Method, parameters: Parameters?): UploadRequest {132 val request = Encoding(133 httpMethod = method,134 urlString = path,135 baseUrlString = basePath,136 parameters = if (parameters == null) baseParams else baseParams + parameters137 ).request138 return applyOptions(request).upload()139 }140 fun addRequestInterceptor(interceptor: FoldableRequestInterceptor): FuelManager {141 requestInterceptors += interceptor142 return this143 }144 fun addResponseInterceptor(interceptor: FoldableResponseInterceptor): FuelManager {145 responseInterceptors += interceptor146 return this147 }148 fun removeRequestInterceptor(interceptor: FoldableRequestInterceptor): FuelManager {149 requestInterceptors -= interceptor150 return this151 }152 fun removeResponseInterceptor(interceptor: FoldableResponseInterceptor): FuelManager {153 responseInterceptors -= interceptor154 return this155 }156 fun removeAllRequestInterceptors(): FuelManager {157 requestInterceptors.clear()158 return this159 }160 fun removeAllResponseInterceptors(): FuelManager {161 responseInterceptors.clear()162 return this163 }164 private fun applyOptions(request: Request): Request {165 // Sets base headers ONLY if they are not set166 val unsetBaseHeaders = request.headers.keys.fold(Headers.from(baseHeaders.orEmpty())) {167 result, it -> result.remove(it); result168 }169 return request.header(unsetBaseHeaders).apply {170 executionOptions = RequestExecutionOptions(171 client = client,172 socketFactory = socketFactory,173 hostnameVerifier = hostnameVerifier,174 callbackExecutor = callbackExecutor,175 requestTransformer = requestInterceptors.foldRight({ r: Request -> r }) { f, acc -> f(acc) },176 responseTransformer = responseInterceptors.foldRight({ _: Request, res: Response -> res }) { f, acc -> f(acc) },177 executorService = executorService178 ).also { executor ->179 executor.timeoutInMillisecond = timeoutInMillisecond180 executor.timeoutReadInMillisecond = timeoutReadInMillisecond181 executor.forceMethods = forceMethods182 }183 }184 }185 companion object {186 // manager187 var instance by readWriteLazy { FuelManager() }188 val progressBufferSize: Int get() = instance.progressBufferSize189 }190 /**191 * Create a [Method.GET] [Request] to [path] with [parameters]192 *193 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path194 * @param parameters [Parameters] the optional parameters195 * @return [Request] the request196 */197 override fun get(path: String, parameters: Parameters?): Request =198 request(Method.GET, path, parameters)199 /**200 * Create a [Method.GET] [Request] to [PathStringConvertible.path] with [parameters]201 *202 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path203 * @param parameters [Parameters] the optional parameters204 * @return [Request] the request205 */206 override fun get(convertible: PathStringConvertible, parameters: Parameters?): Request =207 request(Method.GET, convertible, parameters)208 /**209 * Create a [Method.POST] [Request] to [path] with [parameters]210 *211 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path212 * @param parameters [Parameters] the optional parameters213 * @return [Request] the request214 */215 override fun post(path: String, parameters: Parameters?): Request =216 request(Method.POST, path, parameters)217 /**218 * Create a [Method.POST] [Request] to [PathStringConvertible.path] with [parameters]219 *220 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path221 * @param parameters [Parameters] the optional parameters222 * @return [Request] the request223 */224 override fun post(convertible: PathStringConvertible, parameters: Parameters?): Request =225 request(Method.POST, convertible, parameters)226 /**227 * Create a [Method.PUT] [Request] to [path] with [parameters]228 *229 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path230 * @param parameters [Parameters] the optional parameters231 * @return [Request] the request232 */233 override fun put(path: String, parameters: Parameters?): Request =234 request(Method.PUT, path, parameters)235 /**236 * Create a [Method.PUT] [Request] to [PathStringConvertible.path] with [parameters]237 *238 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path239 * @param parameters [Parameters] the optional parameters240 * @return [Request] the request241 */242 override fun put(convertible: PathStringConvertible, parameters: Parameters?): Request =243 request(Method.PUT, convertible, parameters)244 /**245 * Create a [Method.PATCH] [Request] to [path] with [parameters]246 *247 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path248 * @param parameters [Parameters] the optional parameters249 * @return [Request] the request250 */251 override fun patch(path: String, parameters: Parameters?): Request =252 request(Method.PATCH, path, parameters)253 /**254 * Create a [Method.PATCH] [Request] to [PathStringConvertible.path] with [parameters]255 *256 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path257 * @param parameters [Parameters] the optional parameters258 * @return [Request] the request259 */260 override fun patch(convertible: PathStringConvertible, parameters: Parameters?): Request =261 request(Method.PATCH, convertible, parameters)262 /**263 * Create a [Method.DELETE] [Request] to [path] with [parameters]264 *265 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path266 * @param parameters [Parameters] the optional parameters267 * @return [Request] the request268 */269 override fun delete(path: String, parameters: Parameters?): Request =270 request(Method.DELETE, path, parameters)271 /**272 * Create a [Method.DELETE] [Request] to [PathStringConvertible.path] with [parameters]273 *274 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path275 * @param parameters [Parameters] the optional parameters276 * @return [Request] the request277 */278 override fun delete(convertible: PathStringConvertible, parameters: Parameters?): Request =279 request(Method.DELETE, convertible, parameters)280 /**281 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can download to a file282 *283 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path284 * @param method [Method] the method to download with, defaults to [Method.GET]285 * @param parameters [Parameters] the optional parameters286 * @return [DownloadRequest] the request (extended for download)287 */288 override fun download(convertible: PathStringConvertible, method: Method, parameters: Parameters?): DownloadRequest =289 download(convertible.path, method, parameters)290 /**291 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can upload blobs and292 * Data Parts293 *294 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path295 * @param method [Method] the method to upload with, defaults to [Method.POST]296 * @param parameters [Parameters] the optional parameters297 * @return [UploadRequest] the request (extended for upload)298 */299 override fun upload(convertible: PathStringConvertible, method: Method, parameters: Parameters?): UploadRequest =300 upload(convertible.path, method, parameters)301 /**302 * Create a [Method.HEAD] [Request] to [path] with [parameters]...

Full Screen

Full Screen

DownLoadAppService.kt

Source:DownLoadAppService.kt Github

copy

Full Screen

...21import 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,...

Full Screen

Full Screen

RequestFactory.kt

Source:RequestFactory.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.requests.DownloadRequest4import com.github.kittinunf.fuel.core.requests.UploadRequest5interface RequestFactory {6 /**7 * Make a request using [method] to [convertible]'s path with [parameters]8 *9 * @see FuelManager.instance10 * @see RequestFactory(Method, String, Parameters?)11 *12 * @param method [Method] the HTTP method to make the request with13 * @param convertible [PathStringConvertible]14 * @param parameters [Parameters?] list of parameters15 *16 * @return [Request] the request17 */18 fun request(method: Method, convertible: PathStringConvertible, parameters: Parameters? = null): Request19 /**20 * Make a request using [method] to [path] with [parameters]21 *22 * @see FuelManager.instance23 * @see FuelManager.request24 *25 * @param method [Method] the HTTP method to make the request with26 * @param path [String] the absolute url or relative to [FuelManager.instance] basePath27 * @param parameters [Parameters?] list of parameters28 *29 * @return [Request] the request30 */31 fun request(method: Method, path: String, parameters: Parameters? = null): Request32 /**33 * Make a request using from [convertible]34 *35 * @param convertible [RequestConvertible] the instance that can be turned into a [Request]36 * @return [Request] the request37 */38 fun request(convertible: RequestConvertible): Request39 /**40 * Anything that is a [PathStringConvertible] can be used as [path] parameter with [Fuel]41 */42 interface PathStringConvertible {43 val path: String44 }45 /**46 * Anything that is [RequestConvertible] can be used as [request] with [Fuel.request]47 */48 interface RequestConvertible {49 val request: Request50 }51 interface Convenience : RequestFactory {52 /**53 * Create a [method] [Request] to [path] with [parameters], which can download to a file54 *55 * @parameters path [String] the absolute or relative to [FuelManager.instance]' base-path path56 * @parameters method [Method] the method to download with, defaults to [Method.GET]57 * @parameters parameters [Parameters] the optional parameters58 * @return [DownloadRequest] the request (extended for download)59 */60 fun download(path: String, method: Method = Method.GET, parameters: Parameters? = null): DownloadRequest61 /**62 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can download to a file63 *64 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path65 * @param method [Method] the method to download with, defaults to [Method.GET]66 * @param parameters [Parameters] the optional parameters67 * @return [DownloadRequest] the request (extended for download)68 */69 fun download(convertible: PathStringConvertible, method: Method = Method.GET, parameters: Parameters? = null): DownloadRequest70 /**71 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can upload blobs and72 * Data Parts73 *74 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path75 * @param method [Method] the method to upload with, defaults to [Method.POST]76 * @param parameters [Parameters] the optional parameters77 * @return [UploadRequest] the request (extended for upload)78 */79 fun upload(convertible: PathStringConvertible, method: Method = Method.POST, parameters: Parameters? = null): UploadRequest80 /**81 * Create a [method] [Request] to [path] with [parameters], which can upload blobs and Data Parts82 *83 * @parameters path [String] the absolute or relative to [FuelManager.instance]' base-path path...

Full Screen

Full Screen

Extensions.kt

Source:Extensions.kt Github

copy

Full Screen

...4import 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 ->...

Full Screen

Full Screen

DownloadRequest.kt

Source:DownloadRequest.kt Github

copy

Full Screen

...11typealias LegacyDestinationCallback = (Response, URL) -> File12typealias FileDestinationCallback = (Response, Request) -> File13typealias StreamDestinationCallback = (Response, Request) -> Pair<OutputStream, DestinationAsStreamCallback>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 }68}69fun Request.download(): DownloadRequest = DownloadRequest.enableFor(this)

Full Screen

Full Screen

main.kt

Source:main.kt Github

copy

Full Screen

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 Rename...

Full Screen

Full Screen

Fuel.kt

Source:Fuel.kt Github

copy

Full Screen

...3import 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)...

Full Screen

Full Screen

DataFetchService.kt

Source:DataFetchService.kt Github

copy

Full Screen

1package ro.hibyte.horus.service2import com.github.kittinunf.fuel.core.ResponseResultOf3import com.github.kittinunf.fuel.core.requests.DownloadRequest4import com.github.kittinunf.fuel.core.requests.download5import ro.hibyte.horus.api.JobModelEntity6import java.util.concurrent.TimeoutException7import javax.enterprise.context.Dependent8import javax.inject.Inject9import kotlin.jvm.Throws10@Dependent11class DataFetchService {12 @Inject13 private lateinit var reqestService: RequestService14 fun startJob(jsonBody: String): String {15 return reqestService.postt("datarequest", jsonBody)16 .responseObject(JobModelEntity.JobCreationResponse.Deserializer())17 .third.get().jobId18 }19 @Throws(TimeoutException::class)20 fun getJobStatus(jobId: String): String {21 var tries= 022 while (tries<1000){23 tries++24 val status = reqestService.gett("datarequest/status/$jobId")25 .responseObject(JobModelEntity.JobStatusResponse.Deserializer())26 .third.get().status27 when(status){28 "completed", "failed" -> return status29 }30 Thread.sleep(1000)31 }32 throw TimeoutException()33 }34 fun getJobResult(jobId: String): List<JobModelEntity.JobResultResponsContent> {35 return reqestService.gett("datarequest/jobs/$jobId/result")36 .responseObject(JobModelEntity.JobResultRespons.Deserializer())37 .third.get().content38 }39 fun createOrder(jobId: String, uri: String): ResponseResultOf<JobModelEntity.OrderCreateResponse> {40 val jsonOrder: String = "{\n" +41 " \"jobId\": \"$jobId\",\n" +42 " \"uri\": \"$uri\"\n" +43 "}"44 return reqestService.postt("dataorder", jsonOrder)45 .responseObject(JobModelEntity.OrderCreateResponse.Deserializer())46 }47 fun downloadResult(orderId: String): DownloadRequest {48 return reqestService.gett("dataorder/download/$orderId").download()49 }50}...

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()2val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()3val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()4val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()5val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()6val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()7val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()8val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()9val (request, response, result) = DownloadRequest(url).destination { response, url -> File.createTempFile("temp", ".tmp") }.response()10val (request, response, result) = DownloadRequest(url).destination { response, url -> File.create

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1DownloadRequest(url).destination { response, url ->2File.createTempFile("temp", ".tmp")3}.progress { readBytes, totalBytes ->4println("Downloaded $readBytes/$totalBytes")5}.response { request, response, result ->6}7download(url).destination { response, url ->8File.createTempFile("temp", ".tmp")9}.progress { readBytes, totalBytes ->10println("Downloaded $readBytes/$totalBytes")11}.response { request, response, result ->12}13download(url).destination { response, url ->14File.createTempFile("temp", ".tmp")15}.progress { readBytes, totalBytes ->16println("Downloaded $readBytes/$totalBytes")17}.response { request, response, result ->18}19download(url).destination { response, url ->20File.createTempFile("temp", ".tmp")21}.progress { readBytes, totalBytes ->22println("Downloaded $readBytes/$totalBytes")23}.response { request, response, result ->24}25download(url).destination { response, url ->26File.createTempFile("temp", ".tmp")27}.progress { readBytes, totalBytes ->28println("Downloaded $readBytes/$totalBytes")29}.response { request, response, result ->30}31download(url).destination { response, url ->32File.createTempFile("temp", ".tmp")33}.progress { readBytes, totalBytes ->34println("Downloaded $readBytes/$totalBytes")35}.response { request, response, result ->36}37download(url).destination { response, url ->38File.createTempFile("temp", ".tmp")

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.requests.DownloadRequest2fun main(args: Array<String>) {3 downloadRequest.destination { response, url ->4 val file = File.createTempFile("google", "png")5 file.outputStream().use { output ->6 response.dataStream.copyTo(output)7 }8 }9 downloadRequest.response { result ->10 println(result)11 }12}13Download file using download() extension function of com.github.kittinunf.fuel.Fuel class14import com.github.kittinunf.fuel.Fuel15fun main(args: Array<String>) {16 .destination { response, url ->17 val file = File.createTempFile("google", "png")18 file.outputStream().use { output ->19 response.dataStream.copyTo(output)20 }21 }

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1val downloadRequest = DownloadRequest()2downloadRequest.downloadFile(url, file)3val downloadRequest = DownloadRequest()4downloadRequest.downloadFile(url, file)5val downloadRequest = DownloadRequest()6downloadRequest.downloadFile(url, file)7val downloadRequest = DownloadRequest()8downloadRequest.downloadFile(url, file)9val downloadRequest = DownloadRequest()10downloadRequest.downloadFile(url, file)11val downloadRequest = DownloadRequest()12downloadRequest.downloadFile(url, file)13val downloadRequest = DownloadRequest()14downloadRequest.downloadFile(url, file)15val downloadRequest = DownloadRequest()16downloadRequest.downloadFile(url, file)17val downloadRequest = DownloadRequest()18downloadRequest.downloadFile(url, file)19val downloadRequest = DownloadRequest()20downloadRequest.downloadFile(url, file)21val downloadRequest = DownloadRequest()22downloadRequest.downloadFile(url, file)23val downloadRequest = DownloadRequest()24downloadRequest.downloadFile(url, file)25val downloadRequest = DownloadRequest()26downloadRequest.downloadFile(url, file

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1DownloadRequest(url).destination { _, _ -> file }.responseString { _, _, result ->2 result.fold({ data ->3 println(data)4 }, { err ->5 println(err)6 })7}8DownloadRequest(url).destination { _, _ -> file }.progress { readBytes, totalBytes ->9 println("Progress: $readBytes/$totalBytes")10}.responseString { _, _, result ->11 result.fold({ data ->12 println(data)13 }, { err ->14 println(err)15 })16}17DownloadRequest(url).destination { _, _ -> file }.progress { readBytes, totalBytes ->18 println("Progress: $readBytes/$totalBytes")19}.header(headers).responseString { _, _, result ->20 result.fold({ data ->21 println(data)22 }, { err ->23 println(err)24 })25}26DownloadRequest(url).destination { _, _ -> file }.progress { readBytes, totalBytes ->27 println("Progress: $readBytes/$totalBytes")28}.header(headers).parameter(params).responseString { _, _, result ->29 result.fold({ data ->30 println(data)31 }, { err ->32 println(err)33 })34}

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1downloadRequest.downloadFile(url, file)2val downloadRequest = DownloadRequest()3downloadRequest.downloadFile(url, file)4val downloadRequest = DownloadRequest()5downloadRequest.downloadFile(url, file)6val downloadRequest = DownloadRequest()7downloadRequest.downloadFile(url, file)8val downloadRequest = DownloadRequest()9downloadRequest.downloadFile(url, file)10val downloadRequest = DownloadRequest()11downloadRequest.downloadFile(url, file

Full Screen

Full Screen

DownloadRequest

Using AI Code Generation

copy

Full Screen

1DownloadRequest(url).destination { _, _ -> file }.responseString { _, _, result ->2 result.fold({ data ->3 println(data)4 }, { err ->5 println(err)6 })7}8DownloadRequest(url).destination { _, _ -> file }.progress { readBytes, totalBytes ->9 println("Progress: $readBytes/$totalBytes")10}.responseString { _, _, result ->11 result.fold({ data ->12 println(data)13 }, { err ->14 println(err)15 })16}17DownloadRequest(url).destination { _, _ -> file }.progress { readBytes, totalBytes ->18 println("Progress: $readBytes/$totalBytes")19}.header(headers).responseString { _, _, result ->20 result.fold({ data ->21 println(data)22 }, { err ->23 println(err)24 })25}26DownloadRequest(url).destination { _, _ -> file }.progress { readBytes, totalBytes ->27 println("Progress: $readBytes/$totalBytes")28}.header(headers).parameter(params).responseString { _, _, result ->29 result.fold({ data ->30 println(data)31 }, { err ->32 println(err)33 })34}

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Fuel automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful