forked from OpenFeign/feign
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVertxFeign.java
More file actions
476 lines (429 loc) · 15.3 KB
/
Copy pathVertxFeign.java
File metadata and controls
476 lines (429 loc) · 15.3 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
* Copyright © 2012 The Feign Authors (feign@commonhaus.dev)
*
* 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 feign;
import static feign.Util.checkNotNull;
import static feign.Util.isDefault;
import feign.InvocationHandlerFactory.MethodHandler;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.querymap.FieldQueryMapEncoder;
import feign.vertx.VertxDelegatingContract;
import feign.vertx.VertxHttpClient;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
/**
* Allows Feign interfaces to return Vert.x {@link io.vertx.core.Future Future}s.
*
* @author Alexei KLENIN
* @author Gordon McKinney
*/
public final class VertxFeign extends Feign {
private final ParseHandlersByName targetToHandlersByName;
private final InvocationHandlerFactory factory;
private VertxFeign(
final ParseHandlersByName targetToHandlersByName, final InvocationHandlerFactory factory) {
this.targetToHandlersByName = targetToHandlersByName;
this.factory = factory;
}
public static Builder builder() {
return new Builder();
}
@Override
@SuppressWarnings("unchecked")
public <T> T newInstance(final Target<T> target) {
checkNotNull(target, "Argument target must be not null");
final Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);
final Map<Method, MethodHandler> methodToHandler = new HashMap<>();
final List<DefaultMethodHandler> defaultMethodHandlers = new ArrayList<>();
for (final Method method : target.type().getMethods()) {
if (isDefault(method)) {
final DefaultMethodHandler handler = new DefaultMethodHandler(method);
defaultMethodHandlers.add(handler);
methodToHandler.put(method, handler);
} else {
methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
}
}
final InvocationHandler handler = factory.create(target, methodToHandler);
final T proxy =
(T)
Proxy.newProxyInstance(
target.type().getClassLoader(), new Class<?>[] {target.type()}, handler);
for (final DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
defaultMethodHandler.bindTo(proxy);
}
return proxy;
}
/** VertxFeign builder. */
public static final class Builder extends Feign.Builder {
private Vertx vertx;
private final List<RequestInterceptor> requestInterceptors = new ArrayList<>();
private Logger.Level logLevel = Logger.Level.NONE;
private Contract contract = new VertxDelegatingContract(new Contract.Default());
private Retryer retryer = new Retryer.Default();
private Logger logger = new Logger.NoOpLogger();
private Encoder encoder = new Encoder.Default();
private Decoder decoder = new Decoder.Default();
private QueryMapEncoder queryMapEncoder = new FieldQueryMapEncoder();
private List<Capability> capabilities = new ArrayList<>();
private ErrorDecoder errorDecoder = new ErrorDecoder.Default();
private HttpClientOptions options = new HttpClientOptions();
private long timeout = -1;
private boolean decode404;
private UnaryOperator<HttpClientRequest> requestPreProcessor = UnaryOperator.identity();
/** Unsupported operation. */
@Override
public Builder client(final Client client) {
throw new UnsupportedOperationException();
}
/** Unsupported operation. */
@Override
public Builder invocationHandlerFactory(
final InvocationHandlerFactory invocationHandlerFactory) {
throw new UnsupportedOperationException();
}
/**
* Sets a vertx instance to use to make the client.
*
* @param vertx vertx instance
* @return this builder
*/
public Builder vertx(final Vertx vertx) {
this.vertx = checkNotNull(vertx, "Argument vertx must be not null");
return this;
}
/**
* Sets log level.
*
* @param logLevel log level
* @return this builder
*/
@Override
public Builder logLevel(final Logger.Level logLevel) {
this.logLevel = checkNotNull(logLevel, "Argument logLevel must be not null");
return this;
}
/**
* Sets contract. Provided contract will be wrapped in {@link VertxDelegatingContract}.
*
* @param contract contract
* @return this builder
*/
@Override
public Builder contract(final Contract contract) {
checkNotNull(contract, "Argument contract must be not null");
this.contract = new VertxDelegatingContract(contract);
return this;
}
/**
* Sets retryer.
*
* @param retryer retryer
* @return this builder
*/
@Override
public Builder retryer(final Retryer retryer) {
this.retryer = checkNotNull(retryer, "Argument retryer must be not null");
return this;
}
/**
* Sets logger.
*
* @param logger logger
* @return this builder
*/
@Override
public Builder logger(final Logger logger) {
this.logger = checkNotNull(logger, "Argument logger must be not null");
return this;
}
/**
* Sets encoder.
*
* @param encoder encoder
* @return this builder
*/
@Override
public Builder encoder(final Encoder encoder) {
this.encoder = checkNotNull(encoder, "Argument encoder must be not null");
return this;
}
/**
* Sets decoder.
*
* @param decoder decoder
* @return this builder
*/
@Override
public Builder decoder(final Decoder decoder) {
this.decoder = checkNotNull(decoder, "Argument decoder must be not null");
return this;
}
/**
* Sets query map encoder.
*
* @param queryMapEncoder query map encoder
* @return this builder
*/
@Override
public Builder queryMapEncoder(final QueryMapEncoder queryMapEncoder) {
this.queryMapEncoder =
checkNotNull(queryMapEncoder, "Argument queryMapEncoder must be not null");
return this;
}
/**
* Adds a single capability to the builder.
*
* @param capability capability
* @return this builder
*/
@Override
public Builder addCapability(Capability capability) {
checkNotNull(capability, "Argument capability must be not null");
this.capabilities.add(capability);
return this;
}
/**
* This flag indicates that the {@link #decoder(Decoder) decoder} should process responses with
* 404 status, specifically returning null or empty instead of throwing {@link FeignException}.
*
* <p>All first-party (ex gson) decoders return well-known empty values defined by {@link
* Util#emptyValueOf}. To customize further, wrap an existing {@link #decoder(Decoder) decoder}
* or make your own.
*
* <p>This flag only works with 404, as opposed to all or arbitrary status codes. This was an
* explicit decision: 404 - empty is safe, common and doesn't complicate redirection, retry or
* fallback policy.
*
* @return this builder
*/
@Override
public Builder decode404() {
this.decode404 = true;
return this;
}
/**
* Sets error decoder.
*
* @param errorDecoder error deoceder
* @return this builder
*/
@Override
public Builder errorDecoder(final ErrorDecoder errorDecoder) {
this.errorDecoder = checkNotNull(errorDecoder, "Argument errorDecoder must be not null");
return this;
}
/**
* Sets request options using Vert.x {@link HttpClientOptions}.
*
* @param options {@code HttpClientOptions} for full customization of the underlying Vert.x
* {@link HttpClient}
* @return this builder
*/
public Builder options(final HttpClientOptions options) {
this.options = checkNotNull(options, "Argument options must be not null");
return this;
}
/**
* Sets request options using Feign {@link Request.Options}.
*
* @param options Feign {@code Request.Options} object
* @return this builder
*/
@Override
public Builder options(final Request.Options options) {
checkNotNull(options, "Argument options must be not null");
this.options =
new HttpClientOptions()
.setConnectTimeout(options.connectTimeoutMillis())
.setIdleTimeout(options.readTimeoutMillis());
return this;
}
/**
* Configures the amount of time in milliseconds after which if the request does not return any
* data within the timeout period an {@link java.util.concurrent.TimeoutException} fails the
* request.
*
* <p>Setting zero or a negative {@code value} disables the timeout.
*
* @param timeout The quantity of time in milliseconds.
* @return this builder
*/
public Builder timeout(long timeout) {
this.timeout = timeout;
return this;
}
/**
* Defines operation to execute on each {@link HttpClientRequest} before it is sent. Used to
* make setup on request level.
*
* <p>Example:
*
* <pre>
* var client = VertxFeign
* .builder()
* .vertx(vertx)
* .requestPreProcessor(req -> req.putHeader("version", "v1"));
* </pre>
*
* @param requestPreProcessor operation to execute on each request
* @return updated request
*/
public Builder requestPreProcessor(UnaryOperator<HttpClientRequest> requestPreProcessor) {
this.requestPreProcessor =
checkNotNull(requestPreProcessor, "Argument requestPreProcessor must be not null");
return this;
}
/**
* Adds a single request interceptor to the builder.
*
* @param requestInterceptor request interceptor to add
* @return this builder
*/
@Override
public Builder requestInterceptor(final RequestInterceptor requestInterceptor) {
checkNotNull(requestInterceptor, "Argument requestInterceptor must be not null");
this.requestInterceptors.add(requestInterceptor);
return this;
}
/**
* Sets the full set of request interceptors for the builder, overwriting any previous
* interceptors.
*
* @param requestInterceptors set of request interceptors
* @return this builder
*/
@Override
public Builder requestInterceptors(final Iterable<RequestInterceptor> requestInterceptors) {
checkNotNull(requestInterceptors, "Argument requestInterceptors must be not null");
this.requestInterceptors.clear();
for (final RequestInterceptor requestInterceptor : requestInterceptors) {
this.requestInterceptors.add(requestInterceptor);
}
return this;
}
/**
* Defines target and builds client.
*
* @param apiType API interface
* @param url base URL
* @param <T> class of API interface
* @return built client
*/
@Override
public <T> T target(final Class<T> apiType, final String url) {
checkNotNull(apiType, "Argument apiType must be not null");
checkNotNull(url, "Argument url must be not null");
return target(new Target.HardCodedTarget<>(apiType, url));
}
/**
* Defines target and builds client.
*
* @param target target instance
* @param <T> class of API interface
* @return built client
*/
@Override
public <T> T target(final Target<T> target) {
return build().newInstance(target);
}
@Override
public VertxFeign internalBuild() {
checkNotNull(this.vertx, "Vertx instance wasn't provided in VertxFeign builder");
final VertxHttpClient client =
new VertxHttpClient(vertx, options, timeout, requestPreProcessor);
final VertxMethodHandler.Factory methodHandlerFactory =
new VertxMethodHandler.Factory(
client, retryer, requestInterceptors, logger, logLevel, decode404);
final ParseHandlersByName handlersByName =
new ParseHandlersByName(
contract,
options,
encoder,
decoder,
queryMapEncoder,
capabilities,
errorDecoder,
methodHandlerFactory);
final InvocationHandlerFactory invocationHandlerFactory =
new VertxInvocationHandler.Factory();
return new VertxFeign(handlersByName, invocationHandlerFactory);
}
}
private static final class ParseHandlersByName {
private final Contract contract;
private final HttpClientOptions options;
private final Encoder encoder;
private final Decoder decoder;
private final QueryMapEncoder queryMapEncoder;
private final List<Capability> capabilities;
private final ErrorDecoder errorDecoder;
private final VertxMethodHandler.Factory factory;
private ParseHandlersByName(
final Contract contract,
final HttpClientOptions options,
final Encoder encoder,
final Decoder decoder,
final QueryMapEncoder queryMapEncoder,
final List<Capability> capabilities,
final ErrorDecoder errorDecoder,
final VertxMethodHandler.Factory factory) {
this.contract = contract;
this.options = options;
this.factory = factory;
this.encoder = encoder;
this.decoder = decoder;
this.queryMapEncoder = queryMapEncoder;
this.capabilities = capabilities;
this.errorDecoder = errorDecoder;
}
private Map<String, MethodHandler> apply(final Target<?> target) {
final List<MethodMetadata> metadata = contract.parseAndValidateMetadata(target.type());
final Map<String, MethodHandler> result = new HashMap<>();
for (final MethodMetadata metadatum : metadata) {
RequestTemplateFactoryResolver.BuildTemplateByResolvingArgs buildTemplate;
if (!metadatum.formParams().isEmpty() && metadatum.template().bodyTemplate() == null) {
buildTemplate =
new RequestTemplateFactoryResolver.BuildFormEncodedTemplateFromArgs(
metadatum, encoder, queryMapEncoder, target);
} else if (metadatum.bodyIndex() != null || metadatum.alwaysEncodeBody()) {
buildTemplate =
new RequestTemplateFactoryResolver.BuildEncodedTemplateFromArgs(
metadatum, encoder, queryMapEncoder, target);
} else {
buildTemplate =
new RequestTemplateFactoryResolver.BuildTemplateByResolvingArgs(
metadatum, queryMapEncoder, target);
}
result.put(
metadatum.configKey(),
factory.create(target, metadatum, buildTemplate, decoder, errorDecoder));
}
return result;
}
}
}