Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.internal.from
DefaultRequest.kt
Source:DefaultRequest.kt
...92 * @param map [Map<String, Any>] map of headers to replace. Value can be a list or single value93 * @return [Request] the modified request94 */95 override fun header(map: Map<String, Any>): Request {96 headers.putAll(Headers.from(map))97 return request98 }99 /**100 * Replace the headers with the pairs provided101 *102 * @note In earlier versions the mapOf variant of this function worked differently than the vararg pairs variant,103 * which has been changed to make any call to header(...) always overwrite the values and any call to104 * appendHeader(...) will try to append the value.105 *106 * @see set(header: String, values: Collection<*>)107 * @see set(header: String, value: Any)108 *109 * @param pairs [Pair<String, Any>] map of headers to replace. Value can be a list or single value110 * @return [Request] the modified request111 */112 override fun header(vararg pairs: Pair<String, Any>): Request {113 headers.putAll(Headers.from(*pairs))114 return request115 }116 /**117 * Replace the header with the provided values118 *119 * @see set(header: String, values: Collection<*>)120 *121 * @param header [String] the header to set122 * @param values [List<Any>] the values to set the header to123 * @return [Request] the modified request124 */125 override fun header(header: String, values: Collection<*>) = set(header, values)126 /**127 * Replace the header with the provided value128 *129 * @see set(header: String, values: List<Any>)130 *131 * @param header [String] the header to set132 * @param value [Any] the value to set the header to133 * @return [Request] the modified request134 */135 override fun header(header: String, value: Any): Request = set(header, value)136 /**137 * Replace the header with the provided values138 *139 * @see set(header: String, values: List<Any>)140 *141 * @param header [String] the header to set142 * @param values [Any] the values to set the header to143 * @return [Request] the modified request144 */145 override fun header(header: String, vararg values: Any) = set(header, values.toList())146 /**147 * Appends the value to the header or sets it if there was none yet148 *149 * @param header [String] the header name to append to150 * @param value [Any] the value to be transformed through #toString151 */152 override fun appendHeader(header: String, value: Any): Request {153 headers.append(header, value)154 return request155 }156 /**157 * Appends the value to the header or sets it if there was none yet158 *159 * @param header [String] the header name to append to160 * @param values [Any] the value to be transformed through #toString161 */162 override fun appendHeader(header: String, vararg values: Any): Request {163 headers.append(header, values.toList())164 return request165 }166 /**167 * Append each pair, using the key as header name and value as header content168 *169 * @param pairs [Pair<String, Any>]170 */171 override fun appendHeader(vararg pairs: Pair<String, Any>): Request {172 pairs.forEach { pair -> appendHeader(pair.first, pair.second) }173 return request174 }175 /**176 * Sets the body to be read from a generic body source.177 *178 * @note in earlier versions the body callback would be called multiple times in order to maybe get the size. But179 * that would lead to closed streams being unable to be read. If the size is known, set it before anything else.180 *181 * @param openStream [BodySource] a function that yields a stream182 * @param calculateLength [Number?] size in +bytes+ if it is known183 * @param charset [Charset] the charset to write with184 * @param repeatable [Boolean] loads the body into memory upon reading185 *186 * @return [Request] the request187 */188 override fun body(openStream: BodySource, calculateLength: BodyLength?, charset: Charset, repeatable: Boolean): Request {189 _body = DefaultBody190 .from(openStream = openStream, calculateLength = calculateLength, charset = charset)191 .let { body -> if (repeatable) body.asRepeatable() else body }192 return request193 }194 /**195 * Sets the body from a generic stream196 *197 * @note the stream will be read from the position it's at. Make sure you rewind it if you want it to be read from198 * the start.199 *200 * @param stream [InputStream] a stream to read from201 * @param calculateLength [Number?] size in bytes if it is known202 * @param charset [Charset] the charset to write with203 * @param repeatable [Boolean] loads the body into memory upon reading204 *205 * @return [Request] the request206 */207 override fun body(stream: InputStream, calculateLength: BodyLength?, charset: Charset, repeatable: Boolean) =208 body(openStream = { stream }, calculateLength = calculateLength, charset = charset, repeatable = repeatable)209 /**210 * Sets the body from a byte array211 *212 * @param bytes [ByteArray] the bytes to write213 * @param charset [Charset] the charset to write with214 * @return [Request] the request215 */216 override fun body(bytes: ByteArray, charset: Charset) =217 body(stream = ByteArrayInputStream(bytes), calculateLength = { bytes.size.toLong() }, charset = charset, repeatable = true)218 /**219 * Sets the body from a string220 *221 * @param body [String] the string to write222 * @param charset [Charset] the charset to write with223 * @return [Request] the request224 */225 override fun body(body: String, charset: Charset): Request =226 body(bytes = body.toByteArray(charset), charset = charset)227 .let {228 if (header(Headers.CONTENT_TYPE).lastOrNull().isNullOrBlank())229 header(Headers.CONTENT_TYPE, "text/plain; charset=${charset.name()}")230 else it231 }232 /**233 * Sets the body to the contents of a file.234 *235 * @note this does *NOT* make this a multipart upload. For that you can use the upload request. This function can be236 * used if you want to upload the single contents of a text based file as an inline body.237 *238 * @note when charset is not UTF-8, this forces the client to use chunked encoding, because file.length() gives the239 * length of the file in bytes without considering the charset. If the charset is to be considered, the file needs240 * to be read in its entirety which defeats the purpose of using a file.241 *242 * @param file [File] the file to write to the body243 * @param charset [Charset] the charset to write with244 * @return [Request] the request245 */246 override fun body(file: File, charset: Charset): Request = when (charset) {247 Charsets.UTF_8 -> body({ FileInputStream(file) }, { file.length() }, charset)248 else -> body({ FileInputStream(file) }, null, charset)249 }.let {250 if (header(Headers.CONTENT_TYPE).lastOrNull().isNullOrBlank()) {251 val contentType = URLConnection.guessContentTypeFromName(file.name)252 header(Headers.CONTENT_TYPE, "$contentType; charset=${charset.name()}")253 } else {254 it255 }256 }257 /**258 * Sets the body to a defined [Body]259 *260 * @param body [Body] the body to assign261 * @return [Request] the request262 */263 override fun body(body: Body): Request {264 _body = body265 return request266 }267 /**268 * Add a [ProgressCallback] tracking the [Body] of the [Request]269 *270 * @see body271 * @see com.github.kittinunf.fuel.core.requests.UploadRequest.progress272 *273 * @return self274 */275 override fun requestProgress(handler: ProgressCallback): Request {276 executionOptions.requestProgress += handler277 return request278 }279 /**280 * Add a [ProgressCallback] tracking the [Body] of the [com.github.kittinunf.fuel.core.Response]281 *282 * @see com.github.kittinunf.fuel.core.requests.DownloadRequest.progress283 *284 * @return self285 */286 override fun responseProgress(handler: ProgressCallback): Request {287 executionOptions.responseProgress += handler288 return request289 }290 /**291 * Add a [InterruptCallback] to the [RequestExecutionOptions]292 *293 * @see RequestExecutionOptions.interruptCallbacks294 *295 * @return self296 */297 override fun interrupt(interrupt: InterruptCallback) = request.also {298 it.executionOptions.interruptCallbacks.plusAssign(interrupt)299 }300 /**301 * Overwrite the [Request] [timeout] in milliseconds302 *303 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour304 * @note the default client sets [java.net.HttpURLConnection.setConnectTimeout]305 *306 * @param timeout [Int] timeout in milliseconds307 * @return self308 */309 override fun timeout(timeout: Int) = request.also {310 it.executionOptions.timeoutInMillisecond = timeout311 }312 /**313 * Overwrite the [Request] [timeout] in milliseconds314 *315 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour316 * @note the default client sets [java.net.HttpURLConnection.setReadTimeout]317 *318 * @param timeout [Int] timeout in milliseconds319 * @return self320 */321 override fun timeoutRead(timeout: Int) = request.also {322 it.executionOptions.timeoutReadInMillisecond = timeout323 }324 /**325 * Follow redirects as handled by instances of RedirectInterceptors326 * i.e. [com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor]327 *328 * @note The interceptor must implement this behaviour329 * @note The provided RedirectResponseInterceptor defaults to true330 *331 * @param allowRedirects [Boolean] true if allowing, false if not332 * @return self333 */334 override fun allowRedirects(allowRedirects: Boolean) = request.also {335 it.executionOptions.allowRedirects = allowRedirects336 }337 /**338 * Overwrite [RequestExecutionOptions] http cache usage flag339 *340 * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour341 * @note The default client sends `Cache-Control: none` if this flag is false, defaults to true342 *343 * @see java.net.HttpURLConnection.setUseCaches344 * @param useHttpCache [Boolean] true if suggest client to allow cached responses, false otherwise345 */346 override fun useHttpCache(useHttpCache: Boolean) = request.also {347 it.executionOptions.useHttpCache = useHttpCache348 }349 /**350 * Overwrite [RequestExecutionOptions] response validator block351 *352 * @note The default responseValidator is to throw [com.github.kittinunf.fuel.core.HttpException]353 * @note if the response http status code is not in the range of (100 - 399) which should consider as failure response354 *355 * @param validator [ResponseValidator]356 * @return [Request] the modified request357 */358 override fun validate(validator: ResponseValidator) = request.also {359 it.executionOptions.responseValidator = validator360 }361 /**362 * Attach tag to the request363 *364 * @note tag is a generic purpose tagging for Request. This can be used to attach arbitrarily object to the Request instance.365 * @note Tags internally is represented as hashMap that uses class as a key.366 *367 * @param t [Any]368 * @return [Request] the modified request369 */370 override fun tag(t: Any) = request.also {371 tags[t::class] = t372 }373 /**374 * Return corresponding tag from the request375 *376 * @note tag is a generic purpose tagging for Request. This can be used to attach arbitrarily object to the Request instance.377 * @note Tags internally is represented as hashMap that uses class as a key.378 *379 * @param clazz [KClass]380 * @return [Any] previously attached tag if any, null otherwise381 */382 override fun <T : Any> getTag(clazz: KClass<T>) = tags[clazz] as? T383 override val request: Request get() = this384 /**385 * Returns a string representation of the request.386 *387 * @see com.github.kittinunf.fuel.core.extensions.httpString388 * @see com.github.kittinunf.fuel.core.extensions.cUrlString...
Kkiapay.kt
Source:Kkiapay.kt
...136 (if (sdkConfig.enableSandbox) ::sandboxCheckTransactionStatus137 else ::checkTransactionStatus).invoke(it)138 .responseString { _, _, result ->139 result.fold({ resutlString ->140 val transaction = Gson().fromJson<Transaction>(resutlString, Transaction::class.java)141 sdkListener?.invoke(when(transaction.status){142 "SUCCESS" -> STATUS.SUCCESS143 "INVALID_TRANSACTION" -> STATUS.INVALID_TRANSACTION144 "TRANSACTION_NOT_FOUND" -> STATUS.TRANSACTION_NOT_FOUND145 "FAILED" -> STATUS.FAILED146 else -> STATUS.UNKNOWN147 },148 transaction.transactionId)149 }){fuelError ->150 Log.i("Kkiapay.me", fuelError.toString())151 val theError = Gson().fromJson<Error>(String(fuelError.errorData), Error::class.java)152 theError?.let {error ->153 sdkListener?.invoke(when(error.status) {154 4001 -> STATUS.INVALID_PHONE_NUMBER155 4003 -> STATUS.INVALID_API_KEY156 else -> STATUS.FAILED157 }, null)158 } ?: kotlin.run {159 sdkListener?.invoke(STATUS.FAILED, null)160 }161 }162 }163 } ?: kotlin.run {164 sdkListener?.invoke(STATUS.SUCCESS, null)165 }166 } else167 sdkListener?.invoke(STATUS.SUCCESS, null)168 } ?: let {169 sdkListener?.invoke(STATUS.SUCCESS, null)170 }171 } else{172 sdkListener?.invoke(STATUS.FAILED, null)173 }174 }175 companion object {176 internal const val KKIAPAY_URL = "https://widget-v2.kkiapay.me"177 internal var KKIAPAY_REDIRECT_URL = "http://redirect.kkiapay.me"178 const val KKIAPAY_REQUEST_CODE = 0xABC179 internal const val KKIAPAY_TRANSACTION_ID = "me.kkiapay.uikit.KKIAPAY_TRANSACTION_ID"180 }181}182/**183 * Configure and customize the UI-SDK.184 * Possibility to configure the color [themeColor]185 * and the shop logo [imageResource]186 */187data class SdkConfig(@RawRes private val imageResource: Int = -1, @ColorRes internal val themeColor: Int = -1, var enableSandbox: Boolean = false){188 internal var imageUrl: String = ""189 internal var color: String = ""190 internal fun convertColorToString(context: Context){191 if (themeColor != -1){192 color = String.format("#%06x", ContextCompat.getColor(context, themeColor) and 0xffffff)193 Log.i("Kkiapay.me", color)194 }195 }196 internal fun convertImageResToImageUrl(context: Context){197 if (imageResource != -1){198 val stream = context.resources.openRawResource(imageResource)199 var bitmap = BitmapFactory.decodeStream(stream)200 bitmap = reduceBitmap(bitmap)201 val file = File(context.cacheDir, "${UUID.randomUUID()}.png")202 FileOutputStream(file).use {203 bitmap.compress(Bitmap.CompressFormat.PNG, 0, it)204 it.flush()205 }206 KKiapayApi.uploadFile(file)207 ?.responseString { _, _, result ->208 result.fold({resutlString ->209 val uploadKey = Gson().fromJson<List<Map<String, String>>>(resutlString, List::class.java)210 .first()["fd"]?.trim()211 imageUrl = KKiapayApi.getUploadedFile(uploadKey)?.url?.toString() ?: ""212 }){213 Log.e("Kkiapay.me", it.toString())214 }215 }216 }217 }218 private fun reduceBitmap(original: Bitmap): Bitmap {219 val out = ByteArrayOutputStream()220 original.compress(Bitmap.CompressFormat.WEBP, 100, out)221 return BitmapFactory.decodeStream(ByteArrayInputStream(out.toByteArray()))222 }223}...
Deserializable.kt
Source:Deserializable.kt
...46 }47 }48 private fun reserialize(response: Response, stream: InputStream): Response {49 val length = response.body.length50 response.body = DefaultBody.from({ stream }, length?.let { l -> { l } })51 return response52 }53 /**54 * Deserialize into [T] from an [InputStream]55 *56 * @param inputStream [InputStream] source bytes57 * @return [T] deserialized instance of [T] or null when not applied58 */59 fun deserialize(inputStream: InputStream): T? = null60 /**61 * Deserialize into [T] from a [Reader]62 *63 * @param reader [Reader] source bytes64 * @return [T] deserialized instance of [T] or null when not applied65 */66 fun deserialize(reader: Reader): T? = null67 /**68 * Deserialize into [T] from a [ByteArray]69 *70 * @note it is more efficient to implement the [InputStream] variant.71 *72 * @param bytes [ByteArray] source bytes73 * @return [T] deserialized instance of [T] or null when not applied74 */75 fun deserialize(bytes: ByteArray): T? = null76 /**77 * Deserialize into [T] from a [String]78 *79 * @note it is more efficient to implement the [Reader] variant.80 *81 * @param content [String] source bytes82 * @return [T] deserialized instance of [T] or null when not applied83 */84 fun deserialize(content: String): T? = null85}86/**87 * Deserialize the [Response] to the [this] into a [T] using [U]88 *89 * @see ResponseResultHandler90 *91 * @param deserializable [U] the instance that performs deserialization...
NetworkManager.kt
Source:NetworkManager.kt
...22 private const val UNPARK = "unpark"23 }24 private val userAgent = "Opark/${BuildConfig.VERSION_NAME}"25 private enum class Action { PARK, UNPARK }26 @Suppress("MemberVisibilityCanBePrivate") // Used from subclass in mock flavor27 protected fun readServerFromStorage() = ParkApp.storageManager.getServer()28 /**29 * Makes a http request to the park server to check the current status.30 * @param context context to use to get resources for error messages31 * @param resultReadyListener callback function to be called when the result is ready32 */33 open fun checkStatus(context: Context, resultReadyListener: (Result) -> Unit) {34 val serverUrl = readServerFromStorage()35 if (serverUrl.isBlank()) {36 resultReadyListener(Result.NoServer)37 return38 }39 Fuel.get(serverUrl + STATUS)40 .header(mapOf("User-Agent" to userAgent))41 .responseJson { _, _, result ->42 when (result) {43 is com.github.kittinunf.result.Result.Failure -> {44 val (_, fuelError) = result45 resultReadyListener(Result.Fail(null, context.getString(R.string.failed_to_update_generic, fuelError)))46 }47 is com.github.kittinunf.result.Result.Success -> {48 try {49 val data: JSONObject = result.getAs<FuelJson>()?.obj() as JSONObject50 val parkedCars = getParkedCarsFromResponse(data)51 resultReadyListener(Result.Success(parkedCars))52 } catch (e: org.json.JSONException) {53 val errorMessage = context.getString(R.string.failed_to_update) +54 "\n" + context.getString(R.string.fail_reason_unknown_data)55 resultReadyListener(Result.Fail(null, errorMessage))56 } catch (e: Exception) {57 val errorMessage = context.getString(R.string.failed_to_update) +58 "\n" + context.getString(R.string.fail_reason_unknown_error)59 resultReadyListener(Result.Fail(null, errorMessage))60 }61 }62 }63 }64 }65 @Suppress("MemberVisibilityCanBePrivate") // Used in mock flavor66 internal fun getParkedCarsFromResponse(data: JSONObject): List<ParkedCar> {67 val usedSpots: JSONArray = data.getJSONArray("used")68 val parkedCars: MutableList<ParkedCar> = mutableListOf()69 for (index in 0 until usedSpots.length()) {70 val regNo: String = usedSpots.getJSONObject(index).getString("regno")71 val owner: String = usedSpots.getJSONObject(index).getString("user")72 val startTime: String = usedSpots.getJSONObject(index).getString("start")73 parkedCars.add(ParkedCar(regNo, owner, startTime))74 }75 return parkedCars76 }77 private fun doAction(context: Context, ownCar: OwnCar, action: Action, resultReadyListener: (Result) -> Unit) {78 val serverUrl = readServerFromStorage()79 if (serverUrl.isBlank()) {80 return81 }82 val errorMessage: String83 val url: String84 val parameters: MutableList<Pair<String, Any?>> = mutableListOf()85 parameters.add(Pair("regno", ownCar.regNo))86 when (action) {87 Action.PARK -> {88 errorMessage = context.getString(R.string.failed_to_park, ownCar.regNo)89 url = serverUrl + PARK90 parameters.add(Pair("user", ownCar.owner))91 }92 Action.UNPARK -> {93 errorMessage = context.getString(R.string.failed_to_unpark, ownCar.regNo)94 url = serverUrl + UNPARK95 }96 }97 Fuel.post(url, parameters)98 .header(mapOf("User-Agent" to userAgent))99 .responseJson { _, response, result ->100 when (result) {101 is com.github.kittinunf.result.Result.Success -> {102 try {103 val data: JSONObject = result.getAs<FuelJson>()?.obj() as JSONObject104 val success = data.getString("result") == "ok"105 val parkedCars = getParkedCarsFromResponse(data)106 if (success) {107 resultReadyListener(Result.Success(parkedCars))108 } else {109 resultReadyListener(Result.Fail(parkedCars, errorMessage))110 }111 } catch (e: org.json.JSONException) {112 val msg = "$errorMessage\n" +113 context.getString(R.string.fail_reason_unknown_data)114 resultReadyListener(Result.Fail(null, msg))115 } catch (e: Exception) {116 val msg = "$errorMessage\n" +117 context.getString(R.string.fail_reason_unknown_error)118 resultReadyListener(Result.Fail(null, msg))119 }120 }121 is com.github.kittinunf.result.Result.Failure -> {122 val msg = "$errorMessage\n" +123 "${response.statusCode}: ${response.responseMessage}"124 resultReadyListener(Result.Fail(null, msg))125 }126 }127 }128 }129 /**130 * Makes an http post request to the park server to park a car.131 * @param context context to use to get resources for error messages132 * @param ownCar The car to park.133 * @param resultReadyListener callback function to be called when the result is ready134 */135 open fun parkCar(context: Context, ownCar: OwnCar, resultReadyListener: (Result) -> Unit) =136 doAction(context, ownCar, Action.PARK, resultReadyListener)137 /**138 * Makes an http post request to the park server to unpark a car.139 * @param context context to use to get resources for error messages140 * @param car The car to unpark.141 * @param resultReadyListener callback function to be called when the result is ready142 */143 open fun unparkCar(context: Context, car: OwnCar, resultReadyListener: (Result) -> Unit) =144 doAction(context, car, Action.UNPARK, resultReadyListener)145 /**146 * Makes a request to the Opark backend to register on the wait list.147 * @param context the context to use to get resources for error messages148 * @param token the IdToken used to authenticate the user149 * @param resultReadyListener callback function to be called when the result is ready150 */151 open fun addToWaitList(context: Context, token: String, pushToken: String, resultReadyListener: (Result) -> Unit) {152 val body = "{\"pushToken\": \"$pushToken\"}"153 Fuel.post(context.getString(R.string.url_wait_list_endpoint))154 .authentication()155 .basic(token, "")156 .header(mapOf("Content-Type" to "application/json", "User-Agent" to userAgent))157 .body(body).response { _, response, result ->158 when (result) {159 is com.github.kittinunf.result.Result.Success -> {160 resultReadyListener(Result.AddedToWaitList)161 }162 is com.github.kittinunf.result.Result.Failure -> {163 val errorMessage = context.getString(R.string.wait_list_registration_failed)164 val msg = "$errorMessage\n" +165 "${response.statusCode}: ${response.responseMessage}"166 resultReadyListener(Result.Fail(null, msg))167 }168 }169 }170 }171 /**172 * Makes a request to the Opark backend to remove the user from the wait list.173 * @param context the context to use to get resources for error messages174 * @param token the IdToken used to authenticate the user175 * @param resultReadyListener callback function to be called when the result is ready176 */177 open fun removeFromWaitList(context: Context, token: String, resultReadyListener: (Result) -> Unit) {178 Fuel.delete(context.getString(R.string.url_wait_list_endpoint))179 .authentication()180 .basic(token, "")181 .header(mapOf("User-Agent" to userAgent))182 .response { _, response, result ->183 when (result) {184 is com.github.kittinunf.result.Result.Success -> {185 resultReadyListener(Result.RemovedFromWaitList)186 }...
CustomHttpClient.kt
Source:CustomHttpClient.kt
1/*2 * MIT License3 *4 * Copyright (c) 2017 Kittinun Vantasin5 *6 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated7 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to9 * permit persons to whom the Software is furnished to do so, subject to the following conditions:10 *11 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the12 * Software.13 *14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE15 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR16 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR17 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.18 */19package org.cafejojo.schaapi.validationpipeline.githubinteractor.githubapi20import com.github.kittinunf.fuel.core.Client21import com.github.kittinunf.fuel.core.FuelError22import com.github.kittinunf.fuel.core.Method23import com.github.kittinunf.fuel.core.Request24import com.github.kittinunf.fuel.core.Response25import org.springframework.stereotype.Service26import java.io.BufferedOutputStream27import java.io.ByteArrayInputStream28import java.io.IOException29import java.lang.reflect.Field30import java.lang.reflect.Modifier31import java.net.HttpURLConnection32import java.net.Proxy33import java.net.URLConnection34import java.util.zip.GZIPInputStream35import javax.net.ssl.HttpsURLConnection36/**37 * This class temporarily solves an issue with Java's [HttpsURLConnection], which does not support PATCH requests.38 *39 * This class can be removed when either GitHub supports the `X-HTTP-Method-Override`, which is the recommended40 * solution for dealing with the missing PATCH HTTP verb in [HttpsURLConnection], or when [HttpsURLConnection] gets41 * support for PATCH.42 *43 * This class is a copy of [com.github.kittinunf.fuel.toolbox.HttpClient], with the check/replace for PATCH requests44 * removed.45 */46@Service47@Suppress("TooGenericExceptionCaught", "SwallowedException") // Expected behavior48internal class CustomHttpClient(private val proxy: Proxy? = null) : Client {49 init {50 allowMethods("PATCH")51 }52 override fun executeRequest(request: Request): Response {53 val connection = establishConnection(request) as? HttpURLConnection54 ?: throw IllegalStateException("Connection invalid.")55 try {56 connection.apply {57 connectTimeout = request.timeoutInMillisecond58 readTimeout = request.timeoutReadInMillisecond59 doInput = true60 useCaches = false61 requestMethod = request.method.value62 instanceFollowRedirects = false63 for ((key, value) in request.headers) {64 setRequestProperty(key, value)65 }66 setDoOutput(connection, request.method)67 setBodyIfDoOutput(connection, request)68 }69 val contentEncoding = connection.contentEncoding ?: ""70 return Response(71 url = request.url,72 headers = connection.headerFields.filterKeys { it != null },73 contentLength = connection.contentLength.toLong(),74 statusCode = connection.responseCode,75 responseMessage = connection.responseMessage.orEmpty(),76 dataStream = try {77 val stream = connection.errorStream ?: connection.inputStream78 if (contentEncoding.compareTo("gzip", true) == 0) GZIPInputStream(stream) else stream79 } catch (exception: IOException) {80 connection.errorStream ?: connection.inputStream?.close()81 ByteArrayInputStream(ByteArray(0))82 }83 )84 } catch (exception: Exception) {85 throw FuelError(exception, ByteArray(0), Response(request.url))86 } finally {87 // As per Android documentation, a connection that is not explicitly disconnected88 // will be pooled and reused! So, don't close it as we need inputStream later!89 // connection.disconnect()90 }91 }92 private fun establishConnection(request: Request): URLConnection =93 if (proxy != null) request.url.openConnection(proxy) else request.url.openConnection()94 private fun setBodyIfDoOutput(connection: HttpURLConnection, request: Request) {95 val bodyCallback = request.bodyCallback96 if (bodyCallback != null && connection.doOutput) {97 val contentLength = bodyCallback(request, null, 0)98 if (request.type == Request.Type.UPLOAD)99 connection.setFixedLengthStreamingMode(contentLength.toInt())100 BufferedOutputStream(connection.outputStream).use {101 bodyCallback(request, it, contentLength)102 }103 }104 }105 private fun setDoOutput(connection: HttpURLConnection, method: Method) = when (method) {106 Method.GET, Method.DELETE, Method.HEAD -> connection.doOutput = false107 Method.POST, Method.PUT, Method.PATCH -> connection.doOutput = true108 }109 private fun allowMethods(vararg methods: String) {110 val methodsField = HttpURLConnection::class.java.getDeclaredField("methods").apply {111 isAccessible = true112 }113 Field::class.java.getDeclaredField("modifiers").apply {114 isAccessible = true115 setInt(methodsField, methodsField.modifiers and Modifier.FINAL.inv())116 }117 val newMethods =118 (methodsField.get(null) as? Array<*>)?.filterIsInstance<String>()?.toTypedArray()?.plus(methods)119 methodsField.set(null, newMethods)120 }121}...
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}...
ProxyListener.kt
Source:ProxyListener.kt
2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.requests.write5import com.github.kittinunf.fuel.core.requests.writeln6import com.github.salomonbrys.kotson.fromJson7import com.google.gson.Gson8import com.sun.org.apache.xpath.internal.operations.Bool9import javax.swing.JToggleButton10import javax.swing.JTextField11class ProxyListener(private val requestHookField: JTextField, private val responseHookField: JTextField,12 private val requestHookButton: JToggleButton, private val responseHookButton: JToggleButton,13 private val callbacks: IBurpExtenderCallbacks): IProxyListener {14 override fun processProxyMessage(messageIsRequest: Boolean, message: IInterceptedProxyMessage) {15 val requestHookURL = requestHookField.text16 val responseHookURL = responseHookField.text17 val httpRequestResponse = message.messageInfo18 val messageReference = message.messageReference19 val gson = Gson()20 FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")21 val b2b = BurpToBuddy(callbacks)22 if (!requestHookButton.isSelected && messageIsRequest && requestHookURL != "") {23 val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(httpRequestResponse)24 jsonHttpRequestResponse.addProperty("tool", "proxy")25 jsonHttpRequestResponse.addProperty("reference_id", messageReference)26 jsonHttpRequestResponse.remove("response")27 val (_, response, _) = Fuel.post(requestHookURL).28 body(jsonHttpRequestResponse.toString()).response()29 if (response.statusCode != 200) {30 return31 }32 val modifiedHttpRequest = gson.fromJson<HttpRequestResponse>(String(response.data))33 val originalHttpRequest = gson.fromJson<HttpRequestResponse>(jsonHttpRequestResponse.toString())34 callbacks.stdout.write(modifiedHttpRequest.request.method)35 if (requestHasChangesThatAreNotToRaw(originalHttpRequest, modifiedHttpRequest)) {36 // Build the new "headers" to fit into burp's spec.37 val methodPathVersion = "${modifiedHttpRequest.request.method} ${modifiedHttpRequest.request.path} ${modifiedHttpRequest.request.http_version}"38 val headers = mutableListOf(methodPathVersion)39 headers.addAll(modifiedHttpRequest.request.headers.map({40 "${it.key}: ${it.value}"41 }))42 httpRequestResponse.request = callbacks.helpers.buildHttpMessage(headers,43 callbacks.helpers.base64Decode(modifiedHttpRequest.request.body))44 } else if (originalHttpRequest.request.raw != modifiedHttpRequest.request.raw) {45 httpRequestResponse.request = callbacks.helpers.base64Decode(modifiedHttpRequest.request.raw)46 }47 if (modifiedHttpRequest.comment != "") {48 httpRequestResponse.comment = modifiedHttpRequest.comment49 }50 if (modifiedHttpRequest.highlight != "") {51 httpRequestResponse.highlight = modifiedHttpRequest.highlight52 }53 } else if (!responseHookButton.isSelected && responseHookURL != "") {54 val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(httpRequestResponse)55 jsonHttpRequestResponse.addProperty("reference_id", messageReference)56 jsonHttpRequestResponse.addProperty("tool", "proxy")57 jsonHttpRequestResponse.remove("request")58 val (_, response, _) = Fuel.post(responseHookURL).body(jsonHttpRequestResponse.toString()).responseString()59 if (response.statusCode != 200) {60 return61 }62 val modifiedHttpResponse = gson.fromJson<HttpRequestResponse>(String(response.data))63 val originalHttpResponse = gson.fromJson<HttpRequestResponse>(jsonHttpRequestResponse.toString())64 if (originalHttpResponse.response != null && modifiedHttpResponse.response != null65 && originalHttpResponse.response.raw != modifiedHttpResponse.response.raw) {66 httpRequestResponse.response = callbacks.helpers.base64Decode(modifiedHttpResponse.response.raw)67 }68 if (modifiedHttpResponse.comment != "" ) {69 httpRequestResponse.comment = modifiedHttpResponse.comment70 }71 if (modifiedHttpResponse.highlight != "") {72 httpRequestResponse.highlight = modifiedHttpResponse.highlight73 }74 }75 }76 private fun requestHasChangesThatAreNotToRaw(x: HttpRequestResponse, y: HttpRequestResponse): Boolean {77 return (x.request.method != y.request.method ||...
BintrayRepository.kt
Source:BintrayRepository.kt
...29 }30 return response.isSuccessful31 }32 /**33 * Function for getting all packages from bintray34 */35 fun getAllPackages(needRetry: Boolean = true): List<String> {36 val response = getResponse(BintrayConfig.GET_ALL_PACKAGES_URL)37 if (response.isSuccessful) {38 val data = String(response.data)39 return gson.fromJson(data, Array<BintrayPackageInfoJson>::class.java)40 .toList()41 .map {42 it.transform()43 }44 } else {45 val stringResponse = response.toString()46 when (response.statusCode) {47 HttpStatusCodes.STATUS_CODE_UNAUTHORIZED -> throw UnauthorizedException(stringResponse)48 EMPTY_ERROR_CODE -> {49 if (needRetry) {50 println("$stringResponse\n RETRY ${BintrayConfig.GET_ALL_PACKAGES_URL}")51 return getAllPackages(false)52 } else {53 throw GradleException(stringResponse)54 }55 }56 else -> throw GradleException(stringResponse)57 }58 }59 }60 /**61 * Function for getting the latest version of artifact in bintray62 */63 fun getArtifactLatestVersion(64 artifactName: String,65 needRetry: Boolean = true66 ): BintrayRepoLatestVersion {67 val url = "${BintrayConfig.GET_VERSION_URL}/$artifactName/versions/_latest"68 val response = getResponse(url)69 if (response.isSuccessful) {70 val data = String(response.data)71 return gson.fromJson(data, BintrayRepoLatestVersionJson::class.java).transform()72 } else {73 val stringResponse = response.toString()74 when (response.statusCode) {75 HttpStatusCodes.STATUS_CODE_UNAUTHORIZED -> throw UnauthorizedException(stringResponse)76 EMPTY_ERROR_CODE -> {77 if (needRetry) {78 println("$stringResponse\n RETRY $url")79 return getArtifactLatestVersion(artifactName, false)80 } else {81 throw GradleException(stringResponse)82 }83 }84 else -> throw GradleException(stringResponse)85 }...
from
Using AI Code Generation
1 val (data, error) = result2 println(data)3 println(error)4 println(request.cUrlString())5 println(response)6 -keep class kotlin.Metadata { *; }7 -keep class kotlin.jvm.internal.* { *; }8 -keep class kotlinx.coroutines.* { *; }9 -keep class kotlinx.coroutines.flow.* { *; }10 -keep class kotlinx.coroutines.flow.internal.* { *; }11 -keep class kotlinx.coroutines.flow.internal.CombineKt { *; }12 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$2 { *; }13 -keep class kotlinx.coroutines.flow.internal.CombineKt$zipInternal$2 { *; }14 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$1 { *; }15 -keep class kotlinx.coroutines.flow.internal.CombineKt$zipInternal$1 { *; }16 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$3 { *; }17 -keep class kotlinx.coroutines.flow.internal.CombineKt$zipInternal$3 { *; }18 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$4 { *; }19 -keep class kotlinx.coroutines.flow.internal.CombineKt$zipInternal$4 { *; }20 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$5 { *; }21 -keep class kotlinx.coroutines.flow.internal.CombineKt$zipInternal$5 { *; }22 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$6 { *; }23 -keep class kotlinx.coroutines.flow.internal.CombineKt$zipInternal$6 { *; }24 -keep class kotlinx.coroutines.flow.internal.CombineKt$combineInternal$7 { *; }
from
Using AI Code Generation
1 fun toCurlRequestString(): String2}3fun Request.toCurlRequestString(): String {4 val result = StringBuilder()5 val url = this.url.toString()6 val headers = this.headers.map { "-H '${it.first}: ${it.second}'" }7 result.appendln("curl -v -X $method")8 headers.forEach { result.appendln(it) }9 if (body != null) {10 result.appendln("-d '$body'")11 }12 result.appendln(url)13 return result.toString()14}15println(request.toCurlRequestString())
from
Using AI Code Generation
1private fun RequestTask.execute() {2this.url = this.url.withParameters(this.parameters)3this.url = this.url.withHeaders(this.headers)4val request = this.url.request()5val response = request.response()6val result = Result.of(response.third)7this.callback(result)8}9fun get(url: String, parameters: List<Pair<String, Any?>> = listOf(), headers: List<Pair<String, String>> = listOf(), callback: (Result<ByteArray, FuelError>) -> Unit) {10RequestTask(url, parameters, headers, callback).execute()11}12fun get(url: String, parameters: List<Pair<String, Any?>> = listOf(), headers: List<Pair<String, String>> = listOf()): RequestTask {13val requestTask = RequestTask(url, parameters, headers, null)14requestTask.execute()15}16fun get(url: String, parameters: List<Pair<String, Any?>> = listOf(), headers: List<Pair<String, String>> = listOf(), callback: (RequestTask) -> Unit) {17val requestTask = RequestTask(url, parameters, headers, null)18callback(requestTask)19requestTask.execute()20}21fun get(url: String, parameters: List<Pair<String, Any?>> = listOf(), headers: List<Pair<String, String>> = listOf(), callback: (Result<ByteArray, FuelError>) -> Unit, callbackRequestTask: (RequestTask) -> Unit) {22val requestTask = RequestTask(url, parameters, headers, callback)23callbackRequestTask(requestTask)24requestTask.execute()25}26fun get(url: String, parameters: List<Pair<String, Any?>> = listOf(), headers: List<Pair<String, String>> = listOf(), callbackRequestTask: (RequestTask) -> Unit) {27val requestTask = RequestTask(url, parameters, headers, null)28callbackRequestTask(requestTask)29requestTask.execute()30}
from
Using AI Code Generation
1private fun Request.executeRequest(): Response {2 val response = this.response()3 val (request, response, result) = response4 }5private fun Request.executeRequest(): Response {6 val response = this.response()7 val (request, response, result) = response8 }9private fun Request.executeRequest(): Response {10 val response = this.response()11 val (request, response, result) = response12 }13private fun Request.executeRequest(): Response {14 val response = this.response()15 val (request, response, result) = response16 }17private fun Request.executeRequest(): Response {18 val response = this.response()19 val (request, response, result) = response20 }21private fun Request.executeRequest(): Response {22 val response = this.response()23 val (request, response, result) = response24 }25private fun Request.executeRequest(): Response {26 val response = this.response()27 val (request, response, result) = response28 }29private fun Request.executeRequest(): Response {
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!!