How to use source method of com.github.kittinunf.fuel.core.requests.UploadRequest class

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

Request.kt

Source:Request.kt Github

copy

Full Screen

...339 * @return [ResponseResultOf] the response result of [T]340 */341 fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>): ResponseResultOf<T>342 /**343 * Sets the body to be read from a generic body source.344 *345 * @note in earlier versions the body callback would be called multiple times in order to maybe get the size. But346 * that would lead to closed streams being unable to be read. If the size is known, set it before anything else.347 *348 * @param openStream [BodySource] a function that yields a stream349 * @param calculateLength [Number?] size in +bytes+ if it is known350 * @param charset [Charset] the charset to write with351 * @param repeatable [Boolean] loads the body into memory upon reading352 *353 * @return [Request] the request354 */355 fun body(openStream: BodySource, calculateLength: BodyLength? = null, charset: Charset = Charsets.UTF_8, repeatable: Boolean = false): Request356 /**357 * Sets the body from a generic stream...

Full Screen

Full Screen

DefaultRequest.kt

Source:DefaultRequest.kt Github

copy

Full Screen

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

Full Screen

Full Screen

Zendesk.kt

Source:Zendesk.kt Github

copy

Full Screen

...48import com.saagie.htmltozendeskuploader.model.ArticleAttachment49import com.saagie.htmltozendeskuploader.model.ExistingSection50import com.saagie.htmltozendeskuploader.model.NewSection51import com.saagie.htmltozendeskuploader.model.Translation52import com.saagie.htmltozendeskuploader.zendesk.HtmlToZendeskError.ZendeskRequestError.ResourceDoesNotExist53import com.saagie.htmltozendeskuploader.zendesk.HtmlToZendeskError.ZendeskRequestError.UnexpectedRequestError54import com.saagie.htmltozendeskuploader.zendesk.HtmlToZendeskError.ZendeskRequestError.UnexpectedRequestResult55import com.saagie.htmltozendeskuploader.zendesk.ZendeskRequest.DeleteSection56import java.io.File57import kotlin.reflect.KClass58sealed class ZendeskApiBody {59 data class SectionsBody(val sections: List<ExistingSection>) : ZendeskApiBody()60 data class NewSectionBody(val section: NewSection) : ZendeskApiBody()61 data class ExistingSectionBody(val section: ExistingSection) : ZendeskApiBody()62 data class ArticleBody(val article: Article) : ZendeskApiBody()63 data class ArticlesBody(val articles: List<Article>) : ZendeskApiBody()64 data class TranslationBody(val translation: Translation) : ZendeskApiBody()65 data class TranslationsBody(val translations: List<Translation>) : ZendeskApiBody()66 data class AttachmentIdsBody(val attachmentIds: List<Long>) : ZendeskApiBody()67 data class AttachmentBody(val articleAttachment: ArticleAttachment) : ZendeskApiBody()68 object EmptyBody : ZendeskApiBody()69}70sealed class ZendeskRequest<out T : ZendeskApiBody>(71 val method: Method,72 val path: String,73 val responseType: KClass<out T>,74 open val body: ZendeskApiBody = ZendeskApiBody.EmptyBody75) {76 open fun get(basePath: String) = Fuel.request(method, basePath + path, null)77 .apply {78 this@ZendeskRequest.body.toOption().map { jsonBody(gson.toJson(it)) }79 }80 data class GetSections(val categoryId: Long) : ZendeskRequest<ZendeskApiBody.SectionsBody>(81 GET, "/categories/$categoryId/sections.json", ZendeskApiBody.SectionsBody::class82 )83 data class CreateSection(val categoryId: Long, val section: NewSection) :84 ZendeskRequest<ZendeskApiBody.ExistingSectionBody>(85 POST,86 "/categories/$categoryId/sections.json",87 ZendeskApiBody.ExistingSectionBody::class,88 ZendeskApiBody.NewSectionBody(section)89 )90 data class DeleteSection(val sectionId: Long) : ZendeskRequest<ZendeskApiBody.EmptyBody>(91 DELETE,92 "/sections/$sectionId.json",93 ZendeskApiBody.EmptyBody::class94 )95 data class CreateArticle(val article: Article) : ZendeskRequest<ZendeskApiBody.ArticleBody>(96 POST,97 "/sections/${article.parentSectionId}/articles.json",98 ZendeskApiBody.ArticleBody::class,99 ZendeskApiBody.ArticleBody(article)100 )101 data class GetArticles(val sectionId: Long) : ZendeskRequest<ZendeskApiBody.ArticlesBody>(102 GET,103 "/sections/$sectionId/articles.json",104 ZendeskApiBody.ArticlesBody::class105 )106 data class UploadAttachedImage(val filePath: String) : ZendeskRequest<ZendeskApiBody.AttachmentBody>(107 POST,108 "/articles/attachments.json",109 ZendeskApiBody.AttachmentBody::class110 ) {111 override fun get(basePath: String): UploadRequest = super.get(basePath).upload()112 .add(FileDataPart(name = "file", file = File(filePath)))113 .add(InlineDataPart(name = "inline", content = "true"))114 }115 data class LinkAttachedImage(val articleId: Long, val attachmentIds: List<Long>) :116 ZendeskRequest<ZendeskApiBody.EmptyBody>(117 POST,118 "/articles/$articleId/bulk_attachments.json",119 ZendeskApiBody.EmptyBody::class,120 ZendeskApiBody.AttachmentIdsBody(attachmentIds)121 )122 data class GetArticleTranslations(val articleId: Long, val locale: String) :123 ZendeskRequest<ZendeskApiBody.TranslationsBody>(124 GET,125 "/articles/$articleId/translations.json",126 ZendeskApiBody.TranslationsBody::class127 )128 data class UpdateArticleTranslation(val translation: Translation) :129 ZendeskRequest<ZendeskApiBody.EmptyBody>(130 PUT,131 "/articles/${translation.sourceId}/translations/${translation.locale}.json",132 ZendeskApiBody.EmptyBody::class,133 ZendeskApiBody.TranslationBody(translation)134 )135}136class Zendesk(137 val url: String,138 val user: String,139 val password: String,140 val categoryId: Long,141 val pattern: String? = null142) {143 fun createSectionOrOverwriteIfExist(section: NewSection) =144 (pattern?.let {145 getSectionWithPattern(it, section.parentSectionId)146 } ?: getSection(section.name, section.parentSectionId))147 .flatMap {148 DeleteSection(it.id)149 .run()150 .handleErrorWith {151 when (it) {152 is ResourceDoesNotExist -> Unit.right()153 else -> it.left()154 }155 }156 .also { println("Section for version ${section.name} already exists. Deleting it.") }157 .map { section }158 }159 .handleErrorWith {160 when (it) {161 is ResourceDoesNotExist -> section.right()162 else -> it.left()163 }164 }.flatMap { createSection(it) }165 .map { it.id }166 fun createArticle(article: Article) =167 uploadImages(article)168 .map { attachmentsMapping ->169 attachmentsMapping toT article.replaceImgUrlWithAttachmentUrl(attachmentsMapping)170 }171 .flatmapTupleRight(::postArticle)172 .flatMap { (attachments, articleId) ->173 if (attachments.isNotEmpty())174 linkAttachmentsToArticle(attachments.values, articleId)175 else176 Either.right(article)177 }178 fun publishSection(section: ExistingSection) =179 getArticles(section.id)180 .flatMap { articles ->181 articles.map {182 publishArticle(it)183 }.sequence(Either.applicative()).fix()184 }185 .map { Unit }186 private fun getArticleTranslations(articleId: Long) =187 ZendeskRequest.GetArticleTranslations(articleId, "en-us").run()188 .map {189 it.translations190 }191 private fun getArticles(sectionId: Long) =192 ZendeskRequest.GetArticles(sectionId).run()193 .map {194 it.articles195 }196 private fun updateTranslation(translation: Translation) =197 ZendeskRequest.UpdateArticleTranslation(translation).run()198 private fun publishArticle(article: Article) =199 article.id.rightIfNotNull { HtmlToZendeskError.MissingArticleId }200 .flatMap { getArticleTranslations(it) }201 .flatMap { translations ->202 translations.map { translation ->203 updateTranslation(translation.copy(draft = false))204 }.sequence(Either.applicative()).fix()205 }206 .map { Unit }207 private fun uploadArticleImage(path: String) =208 ZendeskRequest.UploadAttachedImage(path).run()209 .map { it.articleAttachment }210 private fun uploadImages(article: Article) =211 article.getBodyImages()212 .map { it to uploadArticleImage("${article.path.parent}/$it") }213 .map { (imgName, uploadResult) ->214 uploadResult.fold({215 it.left()216 }, {217 (imgName to it).right()218 })219 }220 .sequence(Either.applicative()).fix().map { it.fix().toMap() }221 private fun linkAttachmentsToArticle(attachments: Collection<ArticleAttachment>, articleId: Long) =222 ZendeskRequest.LinkAttachedImage(articleId, attachments.map(ArticleAttachment::id)).run()223 private fun postArticle(article: Article) =224 ZendeskRequest.CreateArticle(article).run()225 .flatMap {226 it.article.id.rightIfNotNull {227 UnexpectedRequestResult("The id of the article that has been created is not set. $it ")228 }229 }230 fun getSection(name: String, parentSectionId: Long? = null) =231 ZendeskRequest.GetSections(categoryId).run()232 .flatMap {233 it.sections.firstOrNone { it.name == name && it.parentSectionId == parentSectionId }234 .toEither { ResourceDoesNotExist }235 }236 private fun getSectionWithPattern(pattern: String, parentSectionId: Long? = null) =237 ZendeskRequest.GetSections(categoryId).run()238 .flatMap {239 it.sections.firstOrNone { section ->240 pattern.toRegex().containsMatchIn(section.name) && section.parentSectionId == parentSectionId241 }.toEither { ResourceDoesNotExist }242 }243 private fun createSection(section: NewSection) =244 ZendeskRequest.CreateSection(categoryId, section)245 .run()246 .map { it.section }247 class ZendeskResponseDeserializable2<T : ZendeskApiBody>(val responseType: KClass<out T>) :248 ResponseDeserializable<T> {249 override fun deserialize(content: String): T = when (responseType) {250 ZendeskApiBody.EmptyBody::class -> ZendeskApiBody.EmptyBody as T251 else -> gson.fromJson(content, responseType.java)252 }253 }254 private fun <T : ZendeskApiBody> ZendeskRequest<T>.run(requestConfigBlock: Request.() -> Unit = {}) =255 get(url)256 .apply(requestConfigBlock)257 .also { println(it) }258 .authentication()259 .basic(user, password)260 .responseObject(ZendeskResponseDeserializable2(responseType))261 .third262 .fold(263 { it.right() },264 {265 when (it.response.statusCode) {266 404 -> ResourceDoesNotExist.left()267 else -> UnexpectedRequestError(it).left()268 }269 })270}271private fun <A, B, C, D> Either<A, Tuple2<B, C>>.flatmapTupleRight(block: (C) -> Either<A, D>) = flatMap {272 it.map(block).sequence(Either.applicative()).fix().map { it.fix() }273}...

Full Screen

Full Screen

UploadBody.kt

Source:UploadBody.kt Github

copy

Full Screen

...47 * @return the body as input stream48 */49 override fun toStream(): InputStream {50 throw UnsupportedOperationException(51 "Conversion `toStream` is not supported on UploadBody, because the source is not a single single stream." +52 "Use `toByteArray` to write the contents to memory or `writeTo` to write the contents to a stream."53 )54 }55 /**56 * Returns the body as a [ByteArray].57 *58 * @note Because the body needs to be read into memory anyway, implementations may choose to make the [Body]59 * readable once more after calling this method, with the original [InputStream] being closed (and release its60 * resources). This also means that if an implementation choose to keep it around, `isConsumed` returns false.61 *62 * @return the entire body63 */64 override fun toByteArray(): ByteArray {65 return ByteArrayOutputStream(length?.toInt() ?: 32)66 .use { stream ->67 writeTo(stream)68 stream.toByteArray()69 }70 .also { result ->71 // The entire body is now in memory, and can act as a regular body72 request.body(DefaultBody.from(73 { ByteArrayInputStream(result) },74 { result.size.toLong() }...

Full Screen

Full Screen

UploadRequest.kt

Source:UploadRequest.kt Github

copy

Full Screen

...89 @Deprecated("Use request.add({ ... }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)90 fun dataParts(dataPartsCallback: (Request, URL) -> Iterable<DataPart>): UploadRequest =91 throw NotImplementedError("request.dataParts has been removed. Use request.add { XXXDataPart(...) } instead.")92 @Deprecated("Use request.add({ FileDataPart(...) }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)93 fun sources(sourcesCallback: (Request, URL) -> Iterable<File>): UploadRequest =94 throw NotImplementedError("request.sources has been removed. Use request.add({ BlobDataPart(...) }, { ... }, ...) instead.")95 @Deprecated("Use request.add { FileDataPart(...)} instead", ReplaceWith("add(sourceCallback)"), DeprecationLevel.ERROR)96 fun source(sourceCallback: (Request, URL) -> File): UploadRequest =97 throw NotImplementedError("request.source has been removed. Use request.add { FileDataPart(...) } instead.")98 @Deprecated("Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead", ReplaceWith(""), DeprecationLevel.ERROR)99 fun name(nameCallback: () -> String): UploadRequest =100 throw NotImplementedError("request.name has been removed. Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead")101 @Deprecated("Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead", ReplaceWith(""), DeprecationLevel.ERROR)102 fun name(newName: String): UploadRequest =103 throw NotImplementedError("request.name has been removed. Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead")104}105fun Request.upload(): UploadRequest = UploadRequest.enableFor(this)...

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1val source = object : RequestSource {2 override fun read(buffer: ByteArray): Int {3 return inputStream.read(buffer)4 }5 override fun close() {6 inputStream.close()7 }8}9val (request, response, result) = Fuel.upload("/post").source { request, url ->10}.response()11val (request, response, result) = Fuel.upload("/post").stream { request, url ->12}.response()13val (request, response, result) = Fuel.upload("/post").file { request, url ->14 File("path/to/file")15}.response()16val (request, response, result) = Fuel.upload("/post").data { request, url ->17}.response()18val (request, response, result) = Fuel.upload("/post").bytes { request, url ->19 "some data".toByteArray()20}.response()21val (request, response, result) = Fuel.upload("/post").parameters { request, url ->22 listOf("a" to "b")23}.response()24val (request, response, result) = Fuel.upload("/post").inputStream { request, url ->25}.response()26val (request, response, result) = Fuel.upload("/post").outputStream { request, url ->27}.response()28val (request, response, result) = Fuel.upload("/post").progress { readBytes, totalBytes ->29 println("readBytes: $readBytes")30 println("totalBytes: $totalBytes")31}.response()

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1.source { request, url -> request.body(“Hello World”) }2.responseString { request, response, result ->3}4.file(“file”, “/path/to/file”)5.responseString { request, response, result ->6}7.file(“file”, “/path/to/file”)8.responseString { request, response, result ->9}10.file(“file”, “/path/to/file”)11.responseString { request, response, result ->12}13.file(“file”, “/path/to/file”)14.responseString { request, response, result ->15}16.file(“file”, “/path/to/file”)17.responseString { request, response, result ->18}19.file(“file”, “/path/to/file”)20.responseString { request, response, result ->21}22.file(“file”, “/path/to/file”)23.responseString { request, response, result ->24}

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1fun uploadFile() {2 val file = File("path/to/file")3 request.source { request, url ->4 val connection = url.openConnection() as HttpURLConnection5 connection.setRequestProperty("Content-Type", request.contentType)6 connection.setRequestProperty("Content-Length", request.contentLength.toString())7 connection.outputStream.use { output ->8 request.dataStream.copyTo(output)9 }10 connection.inputStream.use { input ->11 input.bufferedReader().use { reader ->12 reader.readText()13 }14 }15 }.responseString { request, response, result ->16 println(request)17 println(response)18 println(result)19 }20}21fun downloadFile() {22 val file = File("path/to/file")23 request.source { request, url ->24 val connection = url.openConnection() as HttpURLConnection25 connection.setRequestProperty("Content-Type", request.contentType)26 connection.setRequestProperty("Content-Length", request.contentLength.toString())27 connection.outputStream.use { output ->28 request.dataStream.copyTo(output)29 }30 connection.inputStream.use { input ->31 input.bufferedReader().use { reader ->32 reader.readText()33 }34 }35 }.fileDestination { _, _ ->36 }.response { request, response, result ->37 println(request)38 println(response)39 println(result)40 }41}42fun sendRequest() {43 request.source { request, url ->44 val connection = url.openConnection() as HttpURLConnection45 connection.setRequestProperty("Content-Type", request.contentType)46 connection.setRequestProperty("Content-Length", request.contentLength.toString())47 connection.outputStream.use { output ->48 request.dataStream.copyTo(output)49 }50 connection.inputStream.use { input ->51 input.bufferedReader().use { reader ->52 reader.readText()53 }

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1Fuel.upload("/upload", Method.POST)2.source { request, url ->3}4.response { request, response, result ->5}6Fuel.upload("/upload", Method.POST)7.data { request, url ->8}9.response { request, response, result ->10}11Fuel.upload("/upload", Method.POST)12.file { request, url ->13}14.response { request, response, result ->15}16Fuel.upload("/upload", Method.POST)17.stream { request, url ->18}19.response { request, response, result ->20}21Fuel.upload("/upload", Method.POST)22.bytes { request, url ->23}24.response { request, response, result ->

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1request.source { request, url ->2return@source url.readBytes()3}4request.response { request, response, result ->5}6request.source { request, url ->7return@source url.readText()8}9request.response { request, response, result ->10}11request.source { request, url ->

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