How to use String.httpHead method of com.github.kittinunf.fuel.Fuel class

Best Fuel code snippet using com.github.kittinunf.fuel.Fuel.String.httpHead

Client.kt

Source:Client.kt Github

copy

Full Screen

1/**2 * Created by njasm on 02/07/2017.3 */4package com.github.njasm.kotwave5import com.github.njasm.kotwave.resources.*6import com.github.kittinunf.fuel.core.FuelError7import com.github.kittinunf.fuel.core.Request8import com.github.kittinunf.fuel.core.Response9import com.github.kittinunf.fuel.httpGet10import com.github.kittinunf.fuel.httpHead11import com.github.kittinunf.fuel.httpPost12import com.github.kittinunf.fuel.httpPut13import com.github.kittinunf.result.Result14import com.github.njasm.kotwave.resources.utils.UserCollection15class Client(val clientID: String, val secret: String, val callback: String = "") {16 internal val auth: Auth = Auth(Token())17 internal lateinit var lastRequest: Request18 internal lateinit var lastResponse: Response19 internal var defaultReadTimeout: Int = 6000020 constructor(clientID: String, secret: String) : this(clientID, secret, "")21 fun setReadTimeout(milliseconds: Int) {22 defaultReadTimeout = milliseconds23 }24 fun clientCredentialsAuthentication(user: String, passwd: String) {25 val body = setOf(26 "grant_type" to "password",27 "scope" to "non-expiring", // "*",28 "username" to user,29 "password" to passwd,30 "client_id" to this.clientID,31 "client_secret" to this.secret32 )33 val header = setOf("Content-Type" to "application/x-www-form-urlencoded")34 val (_, _, result) = this.post(API_BASE_URL.pathCombine(API_TOKEN_PATH), body, header)35 val newToken = processResponseString(result, Token::class.java)36 auth.token = newToken37 }38 fun refreshAccessToken(refreshToken: String?) {39 val body = setOf(40 "grant_type" to "refresh_token",41 "redirect_uri" to callback,42 "client_id" to clientID,43 "client_secret" to secret,44 "refresh_token" to (refreshToken ?: auth.refreshToken.orEmpty())45 )46 val header = setOf("Content-Type" to "application/x-www-form-urlencoded")47 val (_, _, result) = this.post(API_BASE_URL.pathCombine(API_TOKEN_PATH), body, header)48 val newToken = processResponseString(result, Token::class.java)49 auth.token = newToken50 }51 fun me(): User {52 val (_, _, result) = this.get(API_BASE_URL.pathCombine(API_ME_RESOURCE))53 val u = processResponseString(result, User::class.java)54 u.client = this55 return u56 }57 @JvmOverloads58 fun get(59 url: String, params: Set<Pair<String, Any>> = emptySet(), headers: Set<Pair<String, Any>> = emptySet()60 ): Triple<Request, Response, Result<String, FuelError>> {61 val req = url.httpGet(params.toList()).timeoutRead(defaultReadTimeout)62 req.apply {63 header("Accept" to "application/json")64 headers.forEach { header(it) }65 }66 guardAgainstExpiredToken()67 auth.addOauthHeader(req)68 return doRequest(req)69 }70 fun post(71 url: String, params: Set<Pair<String, Any>> = emptySet(), headers: Set<Pair<String, Any>> = emptySet()72 ): Triple<Request, Response, Result<String, FuelError>> {73 val req = url.httpPost().timeoutRead(defaultReadTimeout)74 headers.forEach { req.header(it) }75 guardAgainstExpiredToken()76 auth.addOauthHeader(req)77 val strBody = params.getBodyOr("")78 req.body(strBody, Charsets.UTF_8)79 return doRequest(req)80 }81 fun put(82 url: String, params: Set<Pair<String, Any>> = emptySet(), headers: Set<Pair<String, Any>> = emptySet()83 ): Triple<Request, Response, Result<String, FuelError>> {84 val req = url.httpPut().timeoutRead(defaultReadTimeout)85 headers.forEach { req.header(it) }86 guardAgainstExpiredToken()87 auth.addOauthHeader(req)88 val strBody = params.getBodyOr("")89 req.body(strBody, Charsets.UTF_8)90 return doRequest(req)91 }92 fun head(93 url: String, headers: Set<Pair<String, Any>> = emptySet()94 ): Triple<Request, Response, Result<String, FuelError>> = url.httpHead().let { req ->95 req.timeoutRead(defaultReadTimeout)96 headers.forEach { h -> req.header(h) }97 guardAgainstExpiredToken()98 auth.addOauthHeader(req)99 return doRequest(req)100 }101 private fun doRequest(req: Request): Triple<Request, Response, Result<String, FuelError>> =102 with(req.header("User-Agent" to KOTWAVE_LIBRARY_USER_AGENT).responseString()) {103 lastRequest = first104 lastResponse = second105 return this106 }107 fun tracksOf(userId: Int): Array<Track> {108 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }109 val fullUrl = API_BASE_URL.pathCombine(API_USERS_RESOURCE, userId, API_TRACKS_RESOURCE)110 val (_, _, result) = this.get(fullUrl)111 val tracks = processResponseString(result, Array<Track>::class.java)112 tracks.forEach { track: Track -> track.client = this }113 return tracks114 }115 fun commentsOf(userId: Int): Array<Comment> {116 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }117 val fullUrl = API_BASE_URL.pathCombine(API_USERS_RESOURCE, userId, API_COMMENTS_RESOURCE)118 val (_, _, result) = this.get(fullUrl)119 val comments = processResponseString(result, Array<Comment>::class.java)120 comments.forEach { comment: Comment -> comment.client = this }121 return comments122 }123 fun followingsOf(userId: Int): Array<User> {124 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }125 val fullUrl = API_BASE_URL.pathCombine(API_USERS_RESOURCE, userId, API_USER_SUB_FOLLOWINGS_RESOURCE)126 val (_, _, result) = this.get(fullUrl)127 val users = processResponseString(result, UserCollection::class.java)128 users.values().forEach { it.client = this }129 return users.values()130 }131 fun followersOf(userId: Int): Array<User> {132 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }133 val fullUrl = API_BASE_URL.pathCombine(API_USERS_RESOURCE, userId, API_USER_SUB_FOLLOWERS_RESOURCE)134 val (_, _, result) = this.get(fullUrl)135 val users = processResponseString(result, UserCollection::class.java)136 users.values().forEach { it.client = this }137 return users.values()138 }139 fun favoritesOf(userId: Int): Array<Track> {140 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }141 val fullUrl = API_BASE_URL.pathCombine(API_USERS_RESOURCE, userId, API_USER_SUB_FAVORITES_RESOURCE)142 val (_, _, result) = this.get(fullUrl)143 val t = processResponseString(result, Array<Track>::class.java)144 t.forEach { it.client = this }145 return t146 }147 fun connectionsOf(userId: Int): Array<Connection> {148 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }149 val fullUrl = API_BASE_URL.pathCombine(API_CONNECTIONS_RESOURCE)150 val (_, _, result) = this.get(fullUrl)151 val c = processResponseString(result, Array<Connection>::class.java)152 c.forEach { it.client = this }153 return c154 }155 fun appsOf(userId: Int): Array<App> {156 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }157 val fullUrl = API_BASE_URL.pathCombine(API_APPS_RESOURCE)158 val (_, _, result) = this.get(fullUrl)159 val a = processResponseString(result, Array<App>::class.java)160 a.forEach { it.client = this }161 return a162 }163 fun playlistsOf(userId: Int): Array<Playlist> {164 throwIf<IllegalArgumentException>("User ID cannot be negative or zero.") { userId <= 0 }165 val url = API_BASE_URL.pathCombine(API_USERS_RESOURCE, userId, API_PLAYLISTS_RESOURCE)166 val (_, _, result) = get(url)167 val pList = processResponseString(result, Array<Playlist>::class.java)168 pList.forEach { p ->169 p.client = this170 p.user.client = this171 p.tracks().forEach { t -> t.client = this }172 }173 return pList174 }175 fun playlistOf(playlistId: Int): Playlist? {176 throwIf<IllegalArgumentException>("Playlist ID cannot be negative or zero.") { playlistId <= 0 }177 val url = API_BASE_URL.pathCombine(API_PLAYLISTS_RESOURCE, playlistId)178 val (_, _, result) = get(url)179 val p = processResponseString(result, Playlist::class.java)180 p.let { it.client = this }181 return p182 }183 fun resolve(uri: String): String? {184 val fullUrl = API_BASE_URL.pathCombine(API_RESOLVE_RESOURCE)185 val (_, response, result) = this.get(fullUrl, mutableSetOf("url" to uri, "client_id" to this.clientID))186 return when (result) {187 is Result.Success -> response.headers["Location"]?.first()188 else -> null189 }190 }191 fun factoryTrack(): Track = (Track()).let { it.client = this; return it }192 fun factoryComment(): Comment = (Comment()).let { it.client = this; return it }193 fun factoryConnection(): Comment = (Comment()).let { it.client = this; return it }194 private inline fun <reified T : Any, V : Any, E : Exception>195 processResponseString(result: Result<V, E>, returnType: Class<T>): T {196 return when (result) {197 is Result.Failure -> {198 println("ERROR HTTP RESPONSE BODY: ${lastResponse.data.toString(Charsets.UTF_8)}")199 throw result.error200 }201 is Result.Success -> fromJson(result.value.toString().toByteArray(), returnType)202 }203 }204 private fun guardAgainstExpiredToken() =205 if (auth.isTokenExpired()) refreshAccessToken(null) else Unit206}...

Full Screen

Full Screen

CouchDatabaseDocument.kt

Source:CouchDatabaseDocument.kt Github

copy

Full Screen

1/*2 * Copyright 2018 Kouchlin Project3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.kouchlin17import com.github.kittinunf.fuel.httpDelete18import com.github.kittinunf.fuel.httpGet19import com.github.kittinunf.fuel.httpHead20import com.github.kittinunf.fuel.httpPost21import com.github.kittinunf.fuel.httpPut22import mu.KotlinLogging23import org.kouchlin.util.*24private val logger = KotlinLogging.logger {}25class CouchDatabaseDocument(val db: CouchDatabase, val id: String? = null, val rev: String? = null) {26 val documentURI = "${db.dbName}/${id.orEmpty()}"27 fun exists(etag: String? = null): Triple<Int?, String?, STATUS> {28 val headers = configureHeaders(etag = etag)29 val (_, response, _) = documentURI.httpHead()30 .configureAuthentication(db.server)31 .header(headers)32 .response()33 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)34 val contentLenght = response.getHeaderValue<Int?>(CONTENT_LENGHT_HEADER)35 return Triple(contentLenght, responseEtag, response.toStatus())36 }37 inline fun <reified T : Any> get(attachment: Boolean? = null,38 attEncodingInfo: Boolean? = null,39 attsSince: List<String>? = null,40 conflicts: Boolean? = null,41 deletedConflicts: Boolean? = null,42 latest: Boolean? = null,43 localSeq: Boolean? = null,44 meta: Boolean? = null,45 openRevs: List<String>? = null,46 rev: String? = null,47 revs: Boolean? = null,48 revsInfo: Boolean? = null,49 etag: String? = null): Triple<T?, String?, STATUS> {50 val headers = configureHeaders(etag = etag)51 val parameters = configureParameters(attachment = attachment,52 attEncodingInfo = attEncodingInfo,53 attsSince = attsSince,54 conflicts = conflicts,55 deletedConflicts = deletedConflicts,56 latest = latest,57 localSeq = localSeq,58 meta = meta,59 openRevs = openRevs,60 rev = rev,61 revs = revs,62 revsInfo = revsInfo)63 val request = documentURI.httpGet(parameters)64 .configureAuthentication(db.server)65 .header(headers)66 val (_, response, result) = when (T::class.java) {67 String::class.java -> request.responseString()68 else -> request.responseObject(CouchDB.adapter.deserialize(T::class.java))69 }70 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)71 return Triple(result.component1() as T?, responseEtag, response.toStatus())72 }73 private fun saveWithPost(batch: Boolean? = null, content: Any): Triple<SaveResponse?, String?, STATUS> {74 val headers = configureHeaders(contentType = APPLICATION_JSON)75 val queryString = configureParameters(batch = batch)76 .encodeQueryString()77 .let { if (it.isNotEmpty()) "?$it" else it }78 val dbUriWithParams = "${db.dbName}$queryString"79 val (docId, docRev, jsonContent) = CouchDB.adapter.deleteDocumentIdRev(content)80 docId?.let { logger.warn("Doc rev $docId is ignored") }81 docRev?.let { logger.warn("Doc rev $docRev is ignored") }82 val (request, response, result) = dbUriWithParams.httpPost()83 .configureAuthentication(db.server)84 .header(headers)85 .body(jsonContent!!)86 .responseObject(CouchDB.adapter.deserialize(SaveResponse::class.java))87 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)88 logger.info(request.cUrlString())89 return Triple(result.component1(), responseEtag, response.toStatus())90 }91 private fun saveWithPut(rev: String? = null, batch: Boolean? = null, newEdits: Boolean? = null, content: Any): Triple<SaveResponse?, String?, STATUS> {92 val headers = configureHeaders(contentType = APPLICATION_JSON)93 val (docId, docRev, jsonContent) = CouchDB.adapter.deleteDocumentIdRev(content)94 if (docId == null && id == null) {95 throw IllegalArgumentException("Document id should be provided")96 }97 if (docId != null && id != null && id != docId) {98 logger.warn("Document Id $docId included in the document is overridden by parameter $id")99 }100 val queryString = configureParameters(rev = rev ?: docRev,101 batch = batch,102 newEdits = newEdits)103 .encodeQueryString()104 .let { if (it.isNotEmpty()) "?$it" else it }105 val documentUriWithParams = "${db.dbName}/${(id ?: docId).orEmpty()}$queryString"106 val (request, response, result) = documentUriWithParams.httpPut()107 .configureAuthentication(db.server)108 .header(headers)109 .body(jsonContent!!)110 .responseObject(CouchDB.adapter.deserialize(SaveResponse::class.java))111 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)112 logger.info(request.cUrlString())113 return Triple(result.component1(), responseEtag, response.toStatus())114 }115 fun save(rev: String? = null, batch: Boolean? = null, newEdits: Boolean? = null, content: Any): Triple<SaveResponse?, String?, STATUS> {116 val (docId, _, _) = CouchDB.adapter.findDocumentIdRev(content)117 return if (id != null || docId != null) {118 saveWithPut(rev, batch, newEdits, content)119 } else {120 saveWithPost(batch, content)121 }122 }123 fun delete(rev: String, batch: Boolean? = null, fullCommit: Boolean? = null): Triple<SaveResponse?, String?, STATUS> {124 val headers = configureHeaders(fullCommit = fullCommit)125 val parameters = configureParameters(rev = rev, batch = batch)126 val (_, response, result) = documentURI.httpDelete(parameters)127 .configureAuthentication(db.server)128 .header(headers)129 .responseObject(CouchDB.adapter.deserialize(SaveResponse::class.java))130 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)131 return Triple(result.component1(), responseEtag, response.toStatus())132 }133// Copy is a non-standard method in HTTP that is not supported by FUEL library134// fun copy(destination: String, rev: String? = null, batch: Boolean? = null, fullCommit: Boolean? = null): Triple<SaveResponse?, String?, STATUS> { 135// Fuel.request("COPY",)136// }137 fun attachment(name: String) = CouchDatabaseDocAttachment(db, this, name)138}...

Full Screen

Full Screen

RequestStringExtensionTest.kt

Source:RequestStringExtensionTest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.test.MockHttpTestCase6import org.hamcrest.CoreMatchers.equalTo7import org.hamcrest.CoreMatchers.notNullValue8import org.hamcrest.CoreMatchers.nullValue9import org.hamcrest.MatcherAssert.assertThat10import org.junit.After11import org.junit.Before12import org.junit.Test13import java.io.File14import java.net.HttpURLConnection15class RequestStringExtensionTest : MockHttpTestCase() {16 @Before17 fun setupFuelManager() {18 FuelManager.instance.baseHeaders = mapOf("foo" to "bar")19 FuelManager.instance.baseParams = listOf("key" to "value")20 }21 @After22 fun resetFuelManager() {23 FuelManager.instance.reset()24 }25 @Test26 fun httpGet() {27 mock.chain(28 request = mock.request().withMethod(Method.GET.value).withPath("/http-get"),29 response = mock.reflect()30 )31 val (request, response, result) = mock.path("http-get").httpGet().responseString()32 val (data, error) = result33 assertThat(request, notNullValue())34 assertThat(response, notNullValue())35 assertThat(error, nullValue())36 assertThat(data, notNullValue())37 val statusCode = HttpURLConnection.HTTP_OK38 assertThat(response.statusCode, equalTo(statusCode))39 }40 @Test41 fun httpPost() {42 mock.chain(43 request = mock.request().withMethod(Method.POST.value).withPath("/http-post"),44 response = mock.reflect()45 )46 val (request, response, result) = mock.path("http-post").httpPost().responseString()47 val (data, error) = result48 assertThat(request, notNullValue())49 assertThat(response, notNullValue())50 assertThat(error, nullValue())51 assertThat(data, notNullValue())52 val statusCode = HttpURLConnection.HTTP_OK53 assertThat(response.statusCode, equalTo(statusCode))54 }55 @Test56 fun httpPut() {57 mock.chain(58 request = mock.request().withMethod(Method.PUT.value).withPath("/http-put"),59 response = mock.reflect()60 )61 val (request, response, result) = mock.path("http-put").httpPut().responseString()62 val (data, error) = result63 assertThat(request, notNullValue())64 assertThat(response, notNullValue())65 assertThat(error, nullValue())66 assertThat(data, notNullValue())67 val statusCode = HttpURLConnection.HTTP_OK68 assertThat(response.statusCode, equalTo(statusCode))69 }70 @Test71 fun httpPatch() {72 mock.chain(73 request = mock.request().withMethod(Method.PATCH.value).withPath("/http-patch"),74 response = mock.reflect()75 )76 mock.chain(77 request = mock.request()78 .withMethod(Method.POST.value)79 .withHeader("X-HTTP-Method-Override", Method.PATCH.value)80 .withPath("/http-patch"),81 response = mock.reflect()82 )83 val (request, response, result) = mock.path("http-patch").httpPatch().responseString()84 val (data, error) = result85 assertThat(request, notNullValue())86 assertThat(response, notNullValue())87 assertThat(error, nullValue())88 assertThat(data, notNullValue())89 val statusCode = HttpURLConnection.HTTP_OK90 assertThat(response.statusCode, equalTo(statusCode))91 }92 @Test93 fun httpDelete() {94 mock.chain(95 request = mock.request().withMethod(Method.DELETE.value).withPath("/http-delete"),96 response = mock.reflect()97 )98 val (request, response, result) = mock.path("http-delete").httpDelete().responseString()99 val (data, error) = result100 assertThat(request, notNullValue())101 assertThat(response, notNullValue())102 assertThat(error, nullValue())103 assertThat(data, notNullValue())104 val statusCode = HttpURLConnection.HTTP_OK105 assertThat(response.statusCode, equalTo(statusCode))106 }107 @Test108 fun httpDownload() {109 mock.chain(110 request = mock.request().withMethod(Method.GET.value).withPath("/http-download"),111 response = mock.reflect()112 )113 val (request, response, result) = mock.path("http-download")114 .httpDownload()115 .fileDestination { _, _ -> File.createTempFile("http-download.dl", null) }116 .responseString()117 val (data, error) = result118 assertThat(request, notNullValue())119 assertThat(response, notNullValue())120 assertThat(error, nullValue())121 assertThat(data, notNullValue())122 val statusCode = HttpURLConnection.HTTP_OK123 assertThat(response.statusCode, equalTo(statusCode))124 }125 @Test126 fun httpUploadWithPut() {127 mock.chain(128 request = mock.request().withMethod(Method.PUT.value).withPath("/http-upload"),129 response = mock.reflect()130 )131 val (request, response, result) = mock.path("http-upload")132 .httpUpload(method = Method.PUT)133 .add {134 val dir = System.getProperty("user.dir")135 val currentDir = File(dir, "src/test/assets")136 FileDataPart(File(currentDir, "lorem_ipsum_long.tmp"))137 }138 .responseString()139 val (data, error) = result140 assertThat(request, notNullValue())141 assertThat(response, notNullValue())142 assertThat(error, nullValue())143 assertThat(data, notNullValue())144 val statusCode = HttpURLConnection.HTTP_OK145 assertThat(response.statusCode, equalTo(statusCode))146 }147 @Test148 fun httpUploadWithPost() {149 mock.chain(150 request = mock.request().withMethod(Method.POST.value).withPath("/http-upload"),151 response = mock.reflect()152 )153 val (request, response, result) = mock.path("http-upload")154 .httpUpload()155 .add {156 val dir = System.getProperty("user.dir")157 val currentDir = File(dir, "src/test/assets")158 FileDataPart(File(currentDir, "lorem_ipsum_long.tmp"))159 }160 .responseString()161 val (data, error) = result162 assertThat(request, notNullValue())163 assertThat(response, notNullValue())164 assertThat(error, nullValue())165 assertThat(data, notNullValue())166 val statusCode = HttpURLConnection.HTTP_OK167 assertThat(response.statusCode, equalTo(statusCode))168 }169 @Test170 fun httpHead() {171 mock.chain(172 request = mock.request().withMethod(Method.HEAD.value).withPath("/http-head"),173 response = mock.response().withStatusCode(HttpURLConnection.HTTP_OK)174 )175 val (request, response, result) = mock.path("http-head")176 .httpHead()177 .responseString()178 val (data, error) = result179 assertThat(request, notNullValue())180 assertThat(response, notNullValue())181 assertThat(error, nullValue())182 assertThat(data, notNullValue())183 val statusCode = HttpURLConnection.HTTP_OK184 assertThat(response.statusCode, equalTo(statusCode))185 }186}...

Full Screen

Full Screen

CouchDatabaseDocAttachment.kt

Source:CouchDatabaseDocAttachment.kt Github

copy

Full Screen

1/*2 * Copyright 2018 Kouchlin Project3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.kouchlin17import com.github.kittinunf.fuel.httpDelete18import com.github.kittinunf.fuel.httpGet19import com.github.kittinunf.fuel.httpHead20import com.github.kittinunf.fuel.httpPut21import mu.KotlinLogging22import org.kouchlin.domain.Attachment23import org.kouchlin.util.*24private val logger = KotlinLogging.logger {}25class CouchDatabaseDocAttachment(val db: CouchDatabase, val doc: CouchDatabaseDocument, val name: String) {26 private val attachmentURI = "${db.dbName}/${doc.id}/$name"27 fun exists(rev: String? = null, etag: String? = null): Triple<Int?, String?, STATUS> {28 val headers = configureHeaders(etag = etag, rev = rev)29 val (_, response, _) = attachmentURI.httpHead()30 .configureAuthentication(db.server)31 .header(headers)32 .response()33 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)34 val contentLenght = response.getHeaderValue<Int?>(CONTENT_LENGHT_HEADER)35 return Triple(contentLenght, responseEtag, response.toStatus())36 }37 fun get(rev: String? = null, etag: String? = null): Triple<Attachment?, String?, STATUS> {38 val headers = configureHeaders(etag = etag)39 val parameters = configureParameters(rev = rev)40 val (request, response, _) = attachmentURI.httpGet(parameters)41 .configureAuthentication(db.server)42 .header(headers)43 .response()44 logger.info(request.cUrlString())45 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)46 val responseContent = response.getHeaderValue<String?>(CONTENT_TYPE_HEADER)47 val responseStatus = response.toStatus()48 return when (responseStatus) {49 STATUS.OK -> Triple(Attachment(response.data, responseContent!!), responseEtag, response.toStatus())50 else -> Triple(null, null, response.toStatus())51 }52 }53 fun save(data: ByteArray, contentType: String, rev: String? = null): Triple<SaveResponse?, String?, STATUS> {54 val headers = configureHeaders(contentType = contentType)55 val parameters = configureParameters(rev = rev)56 val (_, response, result) = attachmentURI.httpPut(parameters)57 .configureAuthentication(db.server)58 .header(headers)59 .body(data)60 .responseObject(CouchDB.adapter.deserialize(SaveResponse::class.java))61 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)62 return Triple(result.get(), responseEtag, response.toStatus())63 }64 fun save(data: String, contentType: String, rev: String? = null): Triple<SaveResponse?, String?, STATUS> {65 val headers = configureHeaders(contentType = contentType)66 val queryString = configureParameters(rev = rev).encodeQueryString()67 val attachmentUriWithParams = "$attachmentURI?$queryString"68 val (request, response, result) = attachmentUriWithParams.httpPut()69 .configureAuthentication(db.server)70 .header(headers)71 .body(data)72 .responseObject(CouchDB.adapter.deserialize(SaveResponse::class.java))73 logger.info(request.cUrlString())74 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)75 return Triple(result.get(), responseEtag, response.toStatus())76 }77 fun delete(rev: String? = null, batch: Boolean? = null, fullCommit: Boolean? = null): Triple<SaveResponse?, String?, STATUS> {78 val headers = configureHeaders(fullCommit = fullCommit)79 val parameters = configureParameters(rev = rev, batch = batch)80 val (request, response, result) = attachmentURI.httpDelete(parameters)81 .configureAuthentication(db.server)82 .header(headers)83 .responseObject(CouchDB.adapter.deserialize(SaveResponse::class.java))84 logger.info(request.cUrlString())85 val responseEtag = response.getHeaderValue<String?>(ETAG_HEADER)86 return Triple(result.get(), responseEtag, response.toStatus())87 }88}...

Full Screen

Full Screen

Fuel.kt

Source:Fuel.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Parameters5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.RequestFactory7import com.github.kittinunf.fuel.core.requests.DownloadRequest8import com.github.kittinunf.fuel.core.requests.UploadRequest9object Fuel : RequestFactory.Convenience by FuelManager.instance {10 var trace = false11 fun trace(function: () -> String) {12 @Suppress("ConstantConditionIf")13 if (trace) println(function())14 }15 fun reset() = FuelManager.instance.reset()16}17fun String.httpGet(parameters: Parameters? = null): Request =18 Fuel.get(this, parameters)19fun RequestFactory.PathStringConvertible.httpGet(parameter: Parameters? = null): Request =20 this.path.httpGet(parameter)21fun String.httpPost(parameters: Parameters? = null): Request =22 Fuel.post(this, parameters)23fun RequestFactory.PathStringConvertible.httpPost(parameters: Parameters? = null): Request =24 this.path.httpPost(parameters)25fun String.httpPut(parameters: Parameters? = null): Request =26 Fuel.put(this, parameters)27fun RequestFactory.PathStringConvertible.httpPut(parameter: Parameters? = null): Request =28 this.path.httpPut(parameter)29fun String.httpPatch(parameters: Parameters? = null): Request =30 Fuel.patch(this, parameters)31fun RequestFactory.PathStringConvertible.httpPatch(parameter: Parameters? = null): Request =32 this.path.httpPatch(parameter)33fun String.httpDelete(parameters: Parameters? = null): Request =34 Fuel.delete(this, parameters)35fun RequestFactory.PathStringConvertible.httpDelete(parameter: Parameters? = null): Request =36 this.path.httpDelete(parameter)37fun String.httpDownload(parameter: Parameters? = null, method: Method = Method.GET): DownloadRequest =38 Fuel.download(this, method, parameter)39fun RequestFactory.PathStringConvertible.httpDownload(parameters: Parameters? = null, method: Method = Method.GET): DownloadRequest =40 this.path.httpDownload(parameters, method)41fun String.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =42 Fuel.upload(this, method, parameters)43fun RequestFactory.PathStringConvertible.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =44 this.path.httpUpload(parameters, method)45fun String.httpHead(parameters: Parameters? = null): Request =46 Fuel.head(this, parameters)47fun RequestFactory.PathStringConvertible.httpHead(parameters: Parameters? = null): Request =48 this.path.httpHead(parameters)...

Full Screen

Full Screen

HttpFetcher.kt

Source:HttpFetcher.kt Github

copy

Full Screen

1package uk.co.eelpieconsulting.feedlistener.http2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Headers4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpHead7import com.github.kittinunf.result.Result8import org.apache.logging.log4j.LogManager9import java.time.ZoneOffset10import java.time.ZonedDateTime11import java.time.format.DateTimeFormatter12import java.util.*13class HttpFetcher(val userAgent: String, val timeout: Int) {14 private val log = LogManager.getLogger(HttpFetcher::class.java)15 fun head(url: String): Result<Pair<Headers, Int>, FuelError> {16 val (_, response, result) = withCommonRequestProperties(url.httpHead()).response()17 when (result) {18 is Result.Failure -> {19 val ex = result.getException()20 log.warn("Failed to head url '" + url + "'. Status code was " + ex.response.statusCode + " and exception was " + ex.message)21 return Result.error(ex)22 }23 is Result.Success -> {24 log.info("Head response code is: " + response.statusCode)25 return Result.success(Pair(response.headers, response.statusCode))26 }27 }28 }29 fun get(url: String, etag: String?, lastModified: Date?): Result<HttpResult, FuelError> {30 val request = withCommonRequestProperties(url.httpGet())31 etag?.let {32 request.header("If-None-Match", etag)33 }34 lastModified?.let {35 val dateTime = ZonedDateTime.ofInstant(lastModified.toInstant(), ZoneOffset.UTC)36 val ifModifiedSince = dateTime.format(DateTimeFormatter.RFC_1123_DATE_TIME)37 log.info("Appending If-Modified-Since header to request: $ifModifiedSince")38 request.header("If-Modified-Since", ifModifiedSince)39 }40 val (_, response, result) = request.response()41 result.fold({ bytes ->42 val httpResult = HttpResult(bytes = bytes, status = response.statusCode, headers = response.headers)43 return Result.success(httpResult)44 }, { fuelError ->45 log.warn(46 "Failed to fetch from url: " + url + "; status code was: " + fuelError.response.statusCode,47 fuelError.message48 )49 return Result.error(fuelError)50 })51 }52 fun withCommonRequestProperties(request: Request): Request {53 return request.timeout(timeout).timeoutRead(timeout).header("User-Agent", userAgent)54 }55}56class HttpResult(val bytes: ByteArray, val status: Int, val headers: Headers)...

Full Screen

Full Screen

HttpHeadRequestTest.kt

Source:HttpHeadRequestTest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Request4import com.github.kittinunf.fuel.core.Response5import org.hamcrest.CoreMatchers.*6import org.junit.Assert.assertThat7import org.junit.Test8import org.hamcrest.CoreMatchers.`is` as isEqualTo9class HttpHeadRequestTest : BaseTestCase() {10 @Test11 fun httpHeadRequest() {12 var req: Request? = null13 var res: Response? = null14 var data: Any? = null15 var err: FuelError? = null16 "https://www.google.com".httpHead().responseString { request, response, (resData, resErr) ->17 req = request18 res = response19 data = resData20 err = resErr21 }22 assertThat(res?.httpStatusCode, isEqualTo(200))23 assertThat(req, notNullValue())24 assertThat(res, notNullValue())25 assertThat(err, nullValue())26 assertThat(data, notNullValue())27 }28}...

Full Screen

Full Screen

FuelHttpClient.kt

Source:FuelHttpClient.kt Github

copy

Full Screen

1package com.makentoshe.booruchan.network.fuel2import com.github.kittinunf.fuel.httpGet3import com.github.kittinunf.fuel.httpHead4import com.github.kittinunf.fuel.httpPost5import com.makentoshe.booruchan.network.HttpClient6import com.makentoshe.booruchan.network.HttpResult7class FuelHttpClient : HttpClient() {8 override fun get(url: String, params: Map<String, String>): HttpResult {9 return FuelHttpResult(url.httpGet().header(params).response())10 }11 override fun post(url: String, body: ByteArray): HttpResult {12 return FuelHttpResult(url.httpPost().body(body).response())13 }14 override fun head(url: String, params: Map<String, String>): HttpResult {15 return FuelHttpResult(url.httpHead().header(params).response())16 }17}...

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful