-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOkHttpClient.kt
executable file
·202 lines (164 loc) · 6.07 KB
/
OkHttpClient.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package com.openlayer.api.client.okhttp
import com.google.common.collect.ListMultimap
import com.google.common.collect.MultimapBuilder
import com.openlayer.api.core.RequestOptions
import com.openlayer.api.core.http.HttpClient
import com.openlayer.api.core.http.HttpMethod
import com.openlayer.api.core.http.HttpRequest
import com.openlayer.api.core.http.HttpRequestBody
import com.openlayer.api.core.http.HttpResponse
import com.openlayer.api.errors.OpenlayerIoException
import java.io.IOException
import java.io.InputStream
import java.net.Proxy
import java.time.Duration
import java.util.concurrent.CompletableFuture
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.BufferedSink
class OkHttpClient
private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val baseUrl: HttpUrl) :
HttpClient {
private fun getClient(requestOptions: RequestOptions): okhttp3.OkHttpClient {
val timeout = requestOptions.timeout ?: return okHttpClient
return okHttpClient
.newBuilder()
.connectTimeout(timeout)
.readTimeout(timeout)
.writeTimeout(timeout)
.callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
.build()
}
override fun execute(
request: HttpRequest,
requestOptions: RequestOptions,
): HttpResponse {
val call = getClient(requestOptions).newCall(request.toRequest())
return try {
call.execute().toResponse()
} catch (e: IOException) {
throw OpenlayerIoException("Request failed", e)
} finally {
request.body?.close()
}
}
override fun executeAsync(
request: HttpRequest,
requestOptions: RequestOptions,
): CompletableFuture<HttpResponse> {
val future = CompletableFuture<HttpResponse>()
request.body?.run { future.whenComplete { _, _ -> close() } }
val call = getClient(requestOptions).newCall(request.toRequest())
call.enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
future.complete(response.toResponse())
}
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(OpenlayerIoException("Request failed", e))
}
}
)
return future
}
override fun close() {
okHttpClient.dispatcher.executorService.shutdown()
okHttpClient.connectionPool.evictAll()
okHttpClient.cache?.close()
}
private fun HttpRequest.toRequest(): Request {
var body: RequestBody? = body?.toRequestBody()
// OkHttpClient always requires a request body for PUT and POST methods
if (body == null && (method == HttpMethod.PUT || method == HttpMethod.POST)) {
body = "".toRequestBody()
}
val builder = Request.Builder().url(toUrl()).method(method.name, body)
headers.forEach(builder::header)
return builder.build()
}
private fun HttpRequest.toUrl(): String {
url?.let {
return it
}
val builder = baseUrl.newBuilder()
pathSegments.forEach(builder::addPathSegment)
queryParams.forEach(builder::addQueryParameter)
return builder.toString()
}
private fun HttpRequestBody.toRequestBody(): RequestBody {
val mediaType = contentType()?.toMediaType()
val length = contentLength()
return object : RequestBody() {
override fun contentType(): MediaType? {
return mediaType
}
override fun contentLength(): Long {
return length
}
override fun isOneShot(): Boolean {
return !repeatable()
}
override fun writeTo(sink: BufferedSink) {
writeTo(sink.outputStream())
}
}
}
private fun Response.toResponse(): HttpResponse {
val headers = headers.toHeaders()
return object : HttpResponse {
override fun statusCode(): Int {
return code
}
override fun headers(): ListMultimap<String, String> {
return headers
}
override fun body(): InputStream {
return body!!.byteStream()
}
override fun close() {
body!!.close()
}
}
}
private fun Headers.toHeaders(): ListMultimap<String, String> {
val headers =
MultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER)
.arrayListValues()
.build<String, String>()
forEach { pair -> headers.put(pair.first, pair.second) }
return headers
}
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var baseUrl: HttpUrl? = null
// default timeout is 1 minute
private var timeout: Duration = Duration.ofSeconds(60)
private var proxy: Proxy? = null
fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl.toHttpUrl() }
fun timeout(timeout: Duration) = apply { this.timeout = timeout }
fun proxy(proxy: Proxy?) = apply { this.proxy = proxy }
fun build(): OkHttpClient {
return OkHttpClient(
okhttp3.OkHttpClient.Builder()
.connectTimeout(timeout)
.readTimeout(timeout)
.writeTimeout(timeout)
.callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
.proxy(proxy)
.build(),
checkNotNull(baseUrl) { "`baseUrl` is required but was not set" },
)
}
}
}