-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathBaseBuilder.java
More file actions
349 lines (310 loc) · 12.2 KB
/
BaseBuilder.java
File metadata and controls
349 lines (310 loc) · 12.2 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
/*
* 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.ExceptionPropagationPolicy.NONE;
import feign.Feign.ResponseMappingDecoder;
import feign.Logger.NoOpLogger;
import feign.Request.Options;
import feign.codec.Codec;
import feign.codec.Decoder;
import feign.codec.DefaultDecoder;
import feign.codec.DefaultEncoder;
import feign.codec.DefaultErrorDecoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public abstract class BaseBuilder<B extends BaseBuilder<B, T>, T> implements Cloneable {
private final B thisB;
protected List<RequestInterceptor> requestInterceptors = new ArrayList<>();
protected List<ResponseInterceptor> responseInterceptors = new ArrayList<>();
protected Logger.Level logLevel = Logger.Level.NONE;
protected Contract contract = new DefaultContract();
protected Retryer retryer = new DefaultRetryer();
protected Logger logger = new NoOpLogger();
protected Encoder encoder = new DefaultEncoder();
protected Decoder decoder = new DefaultDecoder();
protected boolean closeAfterDecode = true;
protected boolean decodeVoid = false;
protected QueryMapEncoder queryMapEncoder = QueryMap.MapEncoder.FIELD.instance();
protected ErrorDecoder errorDecoder = new DefaultErrorDecoder();
protected Options options = new Options();
protected InvocationHandlerFactory invocationHandlerFactory =
new DefaultInvocationHandlerFactory();
protected boolean dismiss404;
protected ExceptionPropagationPolicy propagationPolicy = NONE;
protected List<Capability> capabilities = new ArrayList<>();
public BaseBuilder() {
super();
thisB = (B) this;
}
public B logLevel(Logger.Level logLevel) {
this.logLevel = logLevel;
return thisB;
}
public B contract(Contract contract) {
this.contract = contract;
return thisB;
}
public B retryer(Retryer retryer) {
this.retryer = retryer;
return thisB;
}
public B logger(Logger logger) {
this.logger = logger;
return thisB;
}
public B encoder(Encoder encoder) {
this.encoder = encoder;
return thisB;
}
public B decoder(Decoder decoder) {
this.decoder = decoder;
return thisB;
}
public B codec(Codec codec) {
this.encoder = codec.encoder();
this.decoder = codec.decoder();
return thisB;
}
/**
* This flag indicates that the response should not be automatically closed upon completion of
* decoding the message. This should be set if you plan on processing the response into a
* lazy-evaluated construct, such as a {@link java.util.Iterator}. Feign standard decoders do not
* have built in support for this flag. If you are using this flag, you MUST also use a custom
* Decoder, and be sure to close all resources appropriately somewhere in the Decoder (you can use
* {@link Util#ensureClosed} for convenience).
*
* @since 9.6
*/
public B doNotCloseAfterDecode() {
this.closeAfterDecode = false;
return thisB;
}
public B decodeVoid() {
this.decodeVoid = true;
return thisB;
}
public B queryMapEncoder(QueryMapEncoder queryMapEncoder) {
this.queryMapEncoder = queryMapEncoder;
return thisB;
}
/** Allows to map the response before passing it to the decoder. */
public B mapAndDecode(ResponseMapper mapper, Decoder decoder) {
this.decoder = new ResponseMappingDecoder(mapper, decoder);
return thisB;
}
/**
* 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. If your server returns a different status for not-found, correct via a custom
* {@link #client(Client) client}.
*
* @since 11.9
*/
public B dismiss404() {
this.dismiss404 = true;
return thisB;
}
/**
* 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. If your server returns a different status for not-found, correct via a custom
* {@link #client(Client) client}.
*
* @since 8.12
* @deprecated use {@link #dismiss404()} instead.
*/
@Deprecated
public B decode404() {
this.dismiss404 = true;
return thisB;
}
public B errorDecoder(ErrorDecoder errorDecoder) {
this.errorDecoder = errorDecoder;
return thisB;
}
public B options(Options options) {
this.options = options;
return thisB;
}
/** Adds a single request interceptor to the builder. */
public B requestInterceptor(RequestInterceptor requestInterceptor) {
this.requestInterceptors.add(requestInterceptor);
return thisB;
}
/**
* Sets the full set of request interceptors for the builder, overwriting any previous
* interceptors.
*/
public B requestInterceptors(Iterable<RequestInterceptor> requestInterceptors) {
this.requestInterceptors.clear();
for (RequestInterceptor requestInterceptor : requestInterceptors) {
this.requestInterceptors.add(requestInterceptor);
}
return thisB;
}
/**
* Sets the full set of request interceptors for the builder, overwriting any previous
* interceptors.
*/
public B responseInterceptors(Iterable<ResponseInterceptor> responseInterceptors) {
this.responseInterceptors.clear();
for (ResponseInterceptor responseInterceptor : responseInterceptors) {
this.responseInterceptors.add(responseInterceptor);
}
return thisB;
}
/** Adds a single response interceptor to the builder. */
public B responseInterceptor(ResponseInterceptor responseInterceptor) {
this.responseInterceptors.add(responseInterceptor);
return thisB;
}
/** Allows you to override how reflective dispatch works inside of Feign. */
public B invocationHandlerFactory(InvocationHandlerFactory invocationHandlerFactory) {
this.invocationHandlerFactory = invocationHandlerFactory;
return thisB;
}
public B exceptionPropagationPolicy(ExceptionPropagationPolicy propagationPolicy) {
this.propagationPolicy = propagationPolicy;
return thisB;
}
public B addCapability(Capability capability) {
this.capabilities.add(capability);
return thisB;
}
@SuppressWarnings("unchecked")
B enrich() {
if (capabilities.isEmpty()) {
return thisB;
}
try {
B clone = (B) thisB.clone();
getFieldsToEnrich()
.forEach(
field -> {
field.setAccessible(true);
try {
final Object originalValue = field.get(clone);
final Object enriched;
if (originalValue instanceof List) {
Type ownerType =
((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
enriched =
((List) originalValue)
.stream()
.map(
value ->
Capability.enrich(
value, (Class<?>) ownerType, capabilities))
.collect(Collectors.toList());
} else {
enriched = Capability.enrich(originalValue, field.getType(), capabilities);
}
field.set(clone, enriched);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("Unable to enrich field " + field, e);
} finally {
field.setAccessible(false);
}
});
// enrich each request interceptor, then enrich the list as a whole
RequestInterceptor[] requestArray =
clone.requestInterceptors.toArray(new RequestInterceptor[0]);
for (int i = 0; i < requestArray.length; i++) {
requestArray[i] =
(RequestInterceptor)
Capability.enrich(requestArray[i], RequestInterceptor.class, capabilities);
}
RequestInterceptors requestInterceptors =
(RequestInterceptors)
Capability.enrich(
new RequestInterceptors(Arrays.asList(requestArray)),
RequestInterceptors.class,
capabilities);
clone.requestInterceptors = requestInterceptors.interceptors();
// enrich each response interceptor, then enrich the list as a whole
ResponseInterceptor[] responseArray =
clone.responseInterceptors.toArray(new ResponseInterceptor[0]);
for (int i = 0; i < responseArray.length; i++) {
responseArray[i] =
(ResponseInterceptor)
Capability.enrich(responseArray[i], ResponseInterceptor.class, capabilities);
}
ResponseInterceptors responseInterceptors =
(ResponseInterceptors)
Capability.enrich(
new ResponseInterceptors(Arrays.asList(responseArray)),
ResponseInterceptors.class,
capabilities);
clone.responseInterceptors = responseInterceptors.interceptors();
return clone;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
List<Field> getFieldsToEnrich() {
return Util.allFields(getClass()).stream()
// exclude anything generated by compiler
.filter(field -> !field.isSynthetic())
// and capabilities itself
.filter(field -> !Objects.equals(field.getName(), "capabilities"))
// and thisB helper field
.filter(field -> !Objects.equals(field.getName(), "thisB"))
// interceptor lists are enriched per-element then as a whole via custom types
.filter(field -> !Objects.equals(field.getName(), "requestInterceptors"))
.filter(field -> !Objects.equals(field.getName(), "responseInterceptors"))
// skip primitive types
.filter(field -> !field.getType().isPrimitive())
// skip enumerations
.filter(field -> !field.getType().isEnum())
.collect(Collectors.toList());
}
public final T build() {
return enrich().internalBuild();
}
protected abstract T internalBuild();
protected ResponseInterceptor.Chain responseInterceptorChain() {
ResponseInterceptor.Chain endOfChain = ResponseInterceptor.Chain.DEFAULT;
ResponseInterceptor.Chain executionChain =
this.responseInterceptors.stream()
.reduce(ResponseInterceptor::andThen)
.map(interceptor -> interceptor.apply(endOfChain))
.orElse(endOfChain);
return (ResponseInterceptor.Chain)
Capability.enrich(executionChain, ResponseInterceptor.Chain.class, capabilities);
}
}