forked from fabric8io/kubernetes-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OkHttpClientImpl.java
279 lines (236 loc) · 8.32 KB
/
OkHttpClientImpl.java
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.okhttp;
import io.fabric8.kubernetes.client.http.HttpClient;
import io.fabric8.kubernetes.client.http.HttpRequest;
import io.fabric8.kubernetes.client.http.HttpResponse;
import io.fabric8.kubernetes.client.utils.Utils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import java.io.IOException;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
public class OkHttpClientImpl implements HttpClient {
static final Map<String, MediaType> MEDIA_TYPES = new ConcurrentHashMap<>();
public static final MediaType JSON = parseMediaType("application/json");
public static final MediaType JSON_PATCH = parseMediaType("application/json-patch+json");
public static final MediaType STRATEGIC_MERGE_JSON_PATCH = parseMediaType("application/strategic-merge-patch+json");
public static final MediaType JSON_MERGE_PATCH = parseMediaType("application/merge-patch+json");
static MediaType parseMediaType(String contentType) {
MediaType result = MediaType.parse(contentType);
MEDIA_TYPES.put(contentType, result);
return result;
}
private abstract class OkHttpAsyncBody<T> implements AsyncBody {
private final BodyConsumer<T> consumer;
private final BufferedSource source;
private final CompletableFuture<Void> done = new CompletableFuture<>();
private OkHttpAsyncBody(BodyConsumer<T> consumer, BufferedSource source) {
this.consumer = consumer;
this.source = source;
}
@Override
public void consume() {
// consume should not block from a callers perspective
try {
httpClient.dispatcher().executorService().execute(() -> {
try {
if (!source.exhausted() && !done.isDone()) {
T value = process(source);
consumer.consume(value, this);
} else {
done.complete(null);
}
} catch (Exception e) {
Utils.closeQuietly(source);
done.completeExceptionally(e);
}
});
} catch (Exception e) {
// executor is likely shutdown
Utils.closeQuietly(source);
done.completeExceptionally(e);
}
}
@Override
public CompletableFuture<Void> done() {
return done;
}
protected abstract T process(BufferedSource source) throws IOException;
@Override
public void cancel() {
Utils.closeQuietly(source);
done.cancel(false);
}
}
static class OkHttpResponseImpl<T> implements HttpResponse<T> {
private final Response response;
private T body;
private Class<T> type;
public OkHttpResponseImpl(Response response, T body) throws IOException {
this.response = response;
this.body = body;
}
public OkHttpResponseImpl(Response response, Class<T> type) throws IOException {
this.response = response;
this.type = type;
ResponseBody responseBody = response.body();
if (responseBody != null) {
if (type == null) {
responseBody.close();
} else if (type == String.class) {
body = (T) responseBody.string();
} else if (type == Reader.class) {
body = (T) responseBody.charStream();
} else if (type == byte[].class) {
body = (T) responseBody.bytes();
} else {
body = (T) responseBody.byteStream();
}
}
}
@Override
public int code() {
return response.code();
}
@Override
public T body() {
return body;
}
@Override
public HttpRequest request() {
return new OkHttpRequestImpl(response.request());
}
@Override
public Optional<HttpResponse<?>> previousResponse() {
Response previous = response.priorResponse() != null ? response.priorResponse() : response;
previous = previous.networkResponse() != null ? previous.networkResponse() : previous;
try {
return Optional.ofNullable(previous == response ? null : new OkHttpResponseImpl<>(previous, type));
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public List<String> headers(String key) {
return response.headers(key);
}
@Override
public Map<String, List<String>> headers() {
return response.headers().toMultimap();
}
}
private final okhttp3.OkHttpClient httpClient;
private final OkHttpClientFactory factory;
public OkHttpClientImpl(OkHttpClient httpClient, OkHttpClientFactory factory) {
this.httpClient = httpClient;
this.factory = factory;
}
@Override
public void close() {
ConnectionPool connectionPool = httpClient.connectionPool();
Dispatcher dispatcher = httpClient.dispatcher();
ExecutorService executorService = httpClient.dispatcher() != null ? httpClient.dispatcher().executorService() : null;
if (dispatcher != null) {
dispatcher.cancelAll();
}
if (connectionPool != null) {
connectionPool.evictAll();
}
if (executorService != null) {
executorService.shutdownNow();
}
}
@Override
public Builder newBuilder() {
return new OkHttpClientBuilderImpl(httpClient.newBuilder(), this.factory);
}
@Override
public CompletableFuture<HttpResponse<AsyncBody>> consumeLines(HttpRequest request,
BodyConsumer<String> consumer) {
Function<BufferedSource, AsyncBody> handler = s -> new OkHttpAsyncBody<String>(consumer, s) {
@Override
protected String process(BufferedSource source) throws IOException {
return source.readUtf8Line();
}
};
return sendAsync(request, handler);
}
@Override
public CompletableFuture<HttpResponse<AsyncBody>> consumeBytes(HttpRequest request,
BodyConsumer<List<ByteBuffer>> consumer) {
Function<BufferedSource, AsyncBody> handler = s -> new OkHttpAsyncBody<List<ByteBuffer>>(consumer, s) {
@Override
protected List<ByteBuffer> process(BufferedSource source) throws IOException {
return Collections.singletonList(ByteBuffer.wrap(source.readByteArray()));
}
};
return sendAsync(request, handler);
}
private CompletableFuture<HttpResponse<AsyncBody>> sendAsync(HttpRequest request,
Function<BufferedSource, AsyncBody> handler) {
CompletableFuture<HttpResponse<AsyncBody>> future = new CompletableFuture<>();
Call call = httpClient.newCall(((OkHttpRequestImpl) request).getRequest());
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
BufferedSource source = response.body().source();
AsyncBody asyncBody = handler.apply(source);
future.complete(new OkHttpResponseImpl<>(response, asyncBody));
}
@Override
public void onFailure(Call call, IOException e) {
future.completeExceptionally(e);
}
});
future.whenComplete((r, t) -> {
if (future.isCancelled()) {
call.cancel();
}
});
return future;
}
@Override
public io.fabric8.kubernetes.client.http.WebSocket.Builder newWebSocketBuilder() {
return new OkHttpWebSocketImpl.BuilderImpl(this.httpClient);
}
public okhttp3.OkHttpClient getOkHttpClient() {
return httpClient;
}
@Override
public HttpRequest.Builder newHttpRequestBuilder() {
return new OkHttpRequestImpl.BuilderImpl();
}
@Override
public Factory getFactory() {
return this.factory;
}
}