-
-
Notifications
You must be signed in to change notification settings - Fork 467
/
GenericResponseService.java
713 lines (668 loc) · 28.9 KB
/
GenericResponseService.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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/*
*
* *
* * *
* * * *
* * * * * Copyright 2019-2022 the original author or authors.
* * * * *
* * * * * 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
* * * * *
* * * * * https://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 org.springdoc.core.service;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.v3.core.util.AnnotationsUtils;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.models.ControllerAdviceInfo;
import org.springdoc.core.models.MethodAttributes;
import org.springdoc.core.parsers.ReturnTypeParser;
import org.springdoc.core.properties.SpringDocConfigProperties;
import org.springdoc.core.providers.JavadocProvider;
import org.springdoc.core.utils.PropertyResolverUtils;
import org.springdoc.core.utils.SpringDocAnnotationsUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.ControllerAdviceBean;
import org.springframework.web.method.HandlerMethod;
import static java.util.Arrays.asList;
import static org.springdoc.core.converters.ConverterUtils.isResponseTypeWrapper;
import static org.springdoc.core.utils.Constants.DEFAULT_DESCRIPTION;
import static org.springdoc.core.utils.SpringDocAnnotationsUtils.extractSchema;
import static org.springdoc.core.utils.SpringDocAnnotationsUtils.getContent;
import static org.springdoc.core.utils.SpringDocAnnotationsUtils.mergeSchema;
/**
* The type Generic response builder.
* @author bnasslahsen
*/
public class GenericResponseService {
/**
* This extension name is used to temporary store
* the exception classes.
*/
private static final String EXTENSION_EXCEPTION_CLASSES = "x-exception-class";
/**
* The Operation builder.
*/
private final OperationService operationService;
/**
* The Return type parsers.
*/
private final List<ReturnTypeParser> returnTypeParsers;
/**
* The Spring doc config properties.
*/
private final SpringDocConfigProperties springDocConfigProperties;
/**
* The Property resolver utils.
*/
private final PropertyResolverUtils propertyResolverUtils;
/**
* The Controller advice infos.
*/
private final List<ControllerAdviceInfo> controllerAdviceInfos = new ArrayList<>();
/**
* The Response entity exception handler class.
*/
private static Class<?> responseEntityExceptionHandlerClass;
/**
* Instantiates a new Generic response builder.
*
* @param operationService the operation builder
* @param returnTypeParsers the return type parsers
* @param springDocConfigProperties the spring doc config properties
* @param propertyResolverUtils the property resolver utils
*/
public GenericResponseService(OperationService operationService, List<ReturnTypeParser> returnTypeParsers,
SpringDocConfigProperties springDocConfigProperties,
PropertyResolverUtils propertyResolverUtils) {
super();
this.operationService = operationService;
this.returnTypeParsers = returnTypeParsers;
this.springDocConfigProperties = springDocConfigProperties;
this.propertyResolverUtils = propertyResolverUtils;
}
/**
* Build api responses.
*
* @param components the components
* @param handlerMethod the handler method
* @param operation the operation
* @param methodAttributes the method attributes
* @return the api responses
*/
public ApiResponses build(Components components, HandlerMethod handlerMethod, Operation operation,
MethodAttributes methodAttributes) {
Map<String, ApiResponse> genericMapResponse = getGenericMapResponse(handlerMethod.getBeanType());
if (springDocConfigProperties.isOverrideWithGenericResponse()) {
genericMapResponse = filterAndEnrichGenericMapResponseByDeclarations(handlerMethod, genericMapResponse);
}
ApiResponses apiResponses = methodAttributes.calculateGenericMapResponse(genericMapResponse);
//Then use the apiResponses from documentation
ApiResponses apiResponsesFromDoc = operation.getResponses();
if (!CollectionUtils.isEmpty(apiResponsesFromDoc))
apiResponsesFromDoc.forEach(apiResponses::addApiResponse);
// for each one build ApiResponse and add it to existing responses
// Fill api Responses
computeResponseFromDoc(components, handlerMethod.getReturnType(), apiResponses, methodAttributes);
buildApiResponses(components, handlerMethod.getReturnType(), apiResponses, methodAttributes);
return apiResponses;
}
/**
* Filters the generic API responses by the declared exceptions.
* If Javadoc comment found for the declaration than it overrides the default description.
*
* @param handlerMethod the method which can have exception declarations
* @param genericMapResponse the default generic API responses
* @return the filtered and enriched responses
*/
private Map<String, ApiResponse> filterAndEnrichGenericMapResponseByDeclarations(HandlerMethod handlerMethod, Map<String, ApiResponse> genericMapResponse) {
Map<String, ApiResponse> result = new HashMap<>();
for (Map.Entry<String, ApiResponse> genericResponse : genericMapResponse.entrySet()) {
Map<String, Object> extensions = genericResponse.getValue().getExtensions();
Set<Class<?>> genericExceptions = (Set<Class<?>>) extensions.get(EXTENSION_EXCEPTION_CLASSES);
for (Class<?> declaredException : handlerMethod.getMethod().getExceptionTypes()) {
if (genericExceptions.contains(declaredException)) {
ApiResponse clone = cloneApiResponse(genericResponse.getValue());
clone.getExtensions().remove(EXTENSION_EXCEPTION_CLASSES);
if (operationService.getJavadocProvider() != null) {
JavadocProvider javadocProvider = operationService.getJavadocProvider();
Map<String, String> javadocThrows = javadocProvider.getMethodJavadocThrows(handlerMethod.getMethod());
String description = javadocThrows.get(declaredException.getName());
if (description == null) {
description = javadocThrows.get(declaredException.getSimpleName());
}
if (description != null && !description.trim().isEmpty()) {
clone.setDescription(description);
}
}
result.put(genericResponse.getKey(), clone);
}
}
}
return result;
}
/**
* Build generic response.
*
* @param components the components
* @param findControllerAdvice the find controller advice
* @param locale the locale
*/
public void buildGenericResponse(Components components, Map<String, Object> findControllerAdvice, Locale locale) {
// ControllerAdvice
for (Map.Entry<String, Object> entry : findControllerAdvice.entrySet()) {
List<Method> methods = new ArrayList<>();
Object controllerAdvice = entry.getValue();
// get all methods with annotation @ExceptionHandler
Class<?> objClz = controllerAdvice.getClass();
if (org.springframework.aop.support.AopUtils.isAopProxy(controllerAdvice))
objClz = org.springframework.aop.support.AopUtils.getTargetClass(controllerAdvice);
ControllerAdviceInfo controllerAdviceInfo = new ControllerAdviceInfo(controllerAdvice);
Arrays.stream(ReflectionUtils.getAllDeclaredMethods(objClz))
.filter(m -> m.isAnnotationPresent(ExceptionHandler.class)
|| isResponseEntityExceptionHandlerMethod(m)
).forEach(methods::add);
// for each one build ApiResponse and add it to existing responses
for (Method method : methods) {
if (!operationService.isHidden(method)) {
RequestMapping reqMappingMethod = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
String[] methodProduces = { springDocConfigProperties.getDefaultProducesMediaType() };
if (reqMappingMethod != null)
methodProduces = reqMappingMethod.produces();
Map<String, ApiResponse> controllerAdviceInfoApiResponseMap = controllerAdviceInfo.getApiResponseMap();
MethodParameter methodParameter = new MethodParameter(method, -1);
ApiResponses apiResponsesOp = new ApiResponses();
MethodAttributes methodAttributes = new MethodAttributes(methodProduces, springDocConfigProperties.getDefaultConsumesMediaType(),
springDocConfigProperties.getDefaultProducesMediaType(), controllerAdviceInfoApiResponseMap, locale);
//calculate JsonView Annotation
methodAttributes.setJsonViewAnnotation(AnnotatedElementUtils.findMergedAnnotation(method, JsonView.class));
//use the javadoc return if present
if (operationService.getJavadocProvider() != null) {
JavadocProvider javadocProvider = operationService.getJavadocProvider();
methodAttributes.setJavadocReturn(javadocProvider.getMethodJavadocReturn(methodParameter.getMethod()));
}
Map<String, ApiResponse> apiResponses = computeResponseFromDoc(components, methodParameter, apiResponsesOp, methodAttributes);
buildGenericApiResponses(components, methodParameter, apiResponsesOp, methodAttributes);
apiResponses.forEach(controllerAdviceInfoApiResponseMap::put);
}
}
synchronized (this) {
controllerAdviceInfos.add(controllerAdviceInfo);
}
}
}
/**
* Is response entity exception handler method boolean.
*
* @param m the m
* @return the boolean
*/
private boolean isResponseEntityExceptionHandlerMethod(Method m) {
if (AnnotatedElementUtils.hasAnnotation(m.getDeclaringClass(), ControllerAdvice.class))
return responseEntityExceptionHandlerClass != null && (responseEntityExceptionHandlerClass.isAssignableFrom(m.getDeclaringClass()) && ReflectionUtils.findMethod(responseEntityExceptionHandlerClass, m.getName(), m.getParameterTypes()) != null);
return false;
}
/**
* Compute response from doc map.
*
* @param components the components
* @param methodParameter the method parameter
* @param apiResponsesOp the api responses op
* @param methodAttributes the method attributes
* @return the map
*/
private Map<String, ApiResponse> computeResponseFromDoc(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
MethodAttributes methodAttributes) {
// Parsing documentation, if present
Set<io.swagger.v3.oas.annotations.responses.ApiResponse> responsesArray = getApiResponses(Objects.requireNonNull(methodParameter.getMethod()));
if (!responsesArray.isEmpty()) {
methodAttributes.setWithApiResponseDoc(true);
for (io.swagger.v3.oas.annotations.responses.ApiResponse apiResponseAnnotations : responsesArray) {
String httpCode = apiResponseAnnotations.responseCode();
ApiResponse apiResponse = new ApiResponse();
if (StringUtils.isNotBlank(apiResponseAnnotations.ref())) {
apiResponse.$ref(apiResponseAnnotations.ref());
apiResponsesOp.addApiResponse(apiResponseAnnotations.responseCode(), apiResponse);
continue;
}
apiResponse.setDescription(propertyResolverUtils.resolve(apiResponseAnnotations.description(), methodAttributes.getLocale()));
buildContentFromDoc(components, apiResponsesOp, methodAttributes, apiResponseAnnotations, apiResponse);
Map<String, Object> extensions = AnnotationsUtils.getExtensions(apiResponseAnnotations.extensions());
if (!CollectionUtils.isEmpty(extensions))
apiResponse.extensions(extensions);
AnnotationsUtils.getHeaders(apiResponseAnnotations.headers(), methodAttributes.getJsonViewAnnotation())
.ifPresent(apiResponse::headers);
apiResponsesOp.addApiResponse(httpCode, apiResponse);
}
}
return apiResponsesOp;
}
/**
* Build content from doc.
*
* @param components the components
* @param apiResponsesOp the api responses op
* @param methodAttributes the method attributes
* @param apiResponseAnnotations the api response annotations
* @param apiResponse the api response
*/
public static void buildContentFromDoc(Components components, ApiResponses apiResponsesOp,
MethodAttributes methodAttributes,
io.swagger.v3.oas.annotations.responses.ApiResponse apiResponseAnnotations,
ApiResponse apiResponse) {
io.swagger.v3.oas.annotations.media.Content[] contentdoc = apiResponseAnnotations.content();
Optional<Content> optionalContent = getContent(contentdoc, new String[0],
methodAttributes.getMethodProduces(), null, components, methodAttributes.getJsonViewAnnotation());
if (apiResponsesOp.containsKey(apiResponseAnnotations.responseCode())) {
// Merge with the existing content
Content existingContent = apiResponsesOp.get(apiResponseAnnotations.responseCode()).getContent();
if (optionalContent.isPresent()) {
Content newContent = optionalContent.get();
if (methodAttributes.isMethodOverloaded() && existingContent != null) {
Arrays.stream(methodAttributes.getMethodProduces()).filter(mediaTypeStr -> (newContent.get(mediaTypeStr) != null)).forEach(mediaTypeStr -> {
if (newContent.get(mediaTypeStr).getSchema() != null)
mergeSchema(existingContent, newContent.get(mediaTypeStr).getSchema(), mediaTypeStr);
});
apiResponse.content(existingContent);
}
else
apiResponse.content(newContent);
}
else {
apiResponse.content(existingContent);
}
}
else {
optionalContent.ifPresent(apiResponse::content);
}
}
/**
* Build generic api responses.
*
* @param components the components
* @param methodParameter the method parameter
* @param apiResponsesOp the api responses op
* @param methodAttributes the method attributes
*/
private void buildGenericApiResponses(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
MethodAttributes methodAttributes) {
if (!CollectionUtils.isEmpty(apiResponsesOp)) {
// API Responses at operation and @ApiResponse annotation
for (Map.Entry<String, ApiResponse> entry : apiResponsesOp.entrySet()) {
String httpCode = entry.getKey();
ApiResponse apiResponse = entry.getValue();
buildApiResponses(components, methodParameter, apiResponsesOp, methodAttributes, httpCode, apiResponse, true);
}
}
else {
// Use response parameters with no description filled - No documentation
// available
String httpCode = evaluateResponseStatus(methodParameter.getMethod(), Objects.requireNonNull(methodParameter.getMethod()).getClass(), true);
ApiResponse apiResponse = methodAttributes.getGenericMapResponse().containsKey(httpCode) ? methodAttributes.getGenericMapResponse().get(httpCode)
: new ApiResponse();
if (httpCode != null)
buildApiResponses(components, methodParameter, apiResponsesOp, methodAttributes, httpCode, apiResponse, true);
}
}
/**
* Build api responses.
*
* @param components the components
* @param methodParameter the method parameter
* @param apiResponsesOp the api responses op
* @param methodAttributes the method attributes
*/
private void buildApiResponses(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
MethodAttributes methodAttributes) {
Map<String, ApiResponse> genericMapResponse = methodAttributes.getGenericMapResponse();
if (!CollectionUtils.isEmpty(apiResponsesOp) && apiResponsesOp.size() > genericMapResponse.size()) {
// API Responses at operation and @ApiResponse annotation
for (Map.Entry<String, ApiResponse> entry : apiResponsesOp.entrySet()) {
String httpCode = entry.getKey();
boolean methodAttributesCondition = !methodAttributes.isMethodOverloaded() || (methodAttributes.isMethodOverloaded() && isValidHttpCode(httpCode, methodParameter));
if (!genericMapResponse.containsKey(httpCode) && methodAttributesCondition) {
ApiResponse apiResponse = entry.getValue();
buildApiResponses(components, methodParameter, apiResponsesOp, methodAttributes, httpCode, apiResponse, false);
}
}
}
else {
// Use response parameters with no description filled - No documentation
// available
String httpCode = evaluateResponseStatus(methodParameter.getMethod(), Objects.requireNonNull(methodParameter.getMethod()).getClass(), false);
ApiResponse apiResponse = new ApiResponse();
if (httpCode != null)
buildApiResponses(components, methodParameter, apiResponsesOp, methodAttributes, httpCode, apiResponse, false);
}
}
/**
* Gets api responses.
*
* @param method the method
* @return the api responses
*/
public Set<io.swagger.v3.oas.annotations.responses.ApiResponse> getApiResponses(Method method) {
Class<?> declaringClass = method.getDeclaringClass();
Set<io.swagger.v3.oas.annotations.responses.ApiResponses> apiResponsesDoc = AnnotatedElementUtils
.findAllMergedAnnotations(method, io.swagger.v3.oas.annotations.responses.ApiResponses.class);
Set<io.swagger.v3.oas.annotations.responses.ApiResponse> responses = apiResponsesDoc.stream()
.flatMap(x -> Stream.of(x.value())).collect(Collectors.toSet());
Set<io.swagger.v3.oas.annotations.responses.ApiResponses> apiResponsesDocDeclaringClass = AnnotatedElementUtils
.findAllMergedAnnotations(declaringClass, io.swagger.v3.oas.annotations.responses.ApiResponses.class);
responses.addAll(
apiResponsesDocDeclaringClass.stream().flatMap(x -> Stream.of(x.value())).collect(Collectors.toSet()));
Set<io.swagger.v3.oas.annotations.responses.ApiResponse> apiResponseDoc = AnnotatedElementUtils
.findMergedRepeatableAnnotations(method, io.swagger.v3.oas.annotations.responses.ApiResponse.class);
responses.addAll(apiResponseDoc);
Set<io.swagger.v3.oas.annotations.responses.ApiResponse> apiResponseDocDeclaringClass = AnnotatedElementUtils
.findMergedRepeatableAnnotations(declaringClass,
io.swagger.v3.oas.annotations.responses.ApiResponse.class);
responses.addAll(apiResponseDocDeclaringClass);
return responses;
}
/**
* Build content content.
*
* @param components the components
* @param methodParameter the method parameter
* @param methodProduces the method produces
* @param jsonView the json view
* @return the content
*/
private Content buildContent(Components components, MethodParameter methodParameter, String[] methodProduces, JsonView jsonView) {
Type returnType = getReturnType(methodParameter);
return buildContent(components, methodParameter.getParameterAnnotations(), methodProduces, jsonView, returnType);
}
/**
* Build content content.
*
* @param components the components
* @param annotations the annotations
* @param methodProduces the method produces
* @param jsonView the json view
* @param returnType the return type
* @return the content
*/
public Content buildContent(Components components, Annotation[] annotations, String[] methodProduces, JsonView jsonView, Type returnType) {
Content content = new Content();
// if void, no content
if (isVoid(returnType))
return null;
if (ArrayUtils.isNotEmpty(methodProduces)) {
Schema<?> schemaN = calculateSchema(components, returnType, jsonView, annotations);
if (schemaN != null) {
io.swagger.v3.oas.models.media.MediaType mediaType = new io.swagger.v3.oas.models.media.MediaType();
mediaType.setSchema(schemaN);
// Fill the content
setContent(methodProduces, content, mediaType);
}
}
return content;
}
/**
* Gets return type.
*
* @param methodParameter the method parameter
* @return the return type
*/
private Type getReturnType(MethodParameter methodParameter) {
Type returnType = Object.class;
for (ReturnTypeParser returnTypeParser : returnTypeParsers) {
if (returnType.getTypeName().equals(Object.class.getTypeName())) {
returnType = returnTypeParser.getReturnType(methodParameter);
}
else
break;
}
return returnType;
}
/**
* Calculate schema schema.
*
* @param components the components
* @param returnType the return type
* @param jsonView the json view
* @param annotations the annotations
* @return the schema
*/
private Schema<?> calculateSchema(Components components, Type returnType, JsonView jsonView, Annotation[] annotations) {
if (!isVoid(returnType) && !SpringDocAnnotationsUtils.isAnnotationToIgnore(returnType))
return extractSchema(components, returnType, jsonView, annotations);
return null;
}
/**
* Sets content.
*
* @param methodProduces the method produces
* @param content the content
* @param mediaType the media type
*/
private void setContent(String[] methodProduces, Content content,
io.swagger.v3.oas.models.media.MediaType mediaType) {
Arrays.stream(methodProduces).forEach(mediaTypeStr -> content.addMediaType(mediaTypeStr, mediaType));
}
/**
* Build api responses.
*
* @param components the components
* @param methodParameter the method parameter
* @param apiResponsesOp the api responses op
* @param methodAttributes the method attributes
* @param httpCode the http code
* @param apiResponse the api response
* @param isGeneric the is generic
*/
private void buildApiResponses(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
MethodAttributes methodAttributes, String httpCode, ApiResponse apiResponse, boolean isGeneric) {
// No documentation
if (StringUtils.isBlank(apiResponse.get$ref())) {
if (apiResponse.getContent() == null) {
Content content = buildContent(components, methodParameter, methodAttributes.getMethodProduces(),
methodAttributes.getJsonViewAnnotation());
apiResponse.setContent(content);
}
else if (CollectionUtils.isEmpty(apiResponse.getContent()))
apiResponse.setContent(null);
if (StringUtils.isBlank(apiResponse.getDescription())) {
// use javadoc
if (!StringUtils.isBlank(methodAttributes.getJavadocReturn()))
apiResponse.setDescription(methodAttributes.getJavadocReturn());
else
setDescription(httpCode, apiResponse);
}
}
if (apiResponse.getContent() != null
&& ((isGeneric || methodAttributes.isMethodOverloaded()) && methodAttributes.isNoApiResponseDoc())) {
// Merge with existing schema
Content existingContent = apiResponse.getContent();
Type type = ReturnTypeParser.getType(methodParameter);
Schema<?> schemaN = calculateSchema(components, type,
methodAttributes.getJsonViewAnnotation(), methodParameter.getParameterAnnotations());
if (schemaN != null && ArrayUtils.isNotEmpty(methodAttributes.getMethodProduces()))
Arrays.stream(methodAttributes.getMethodProduces()).forEach(mediaTypeStr -> mergeSchema(existingContent, schemaN, mediaTypeStr));
}
if (springDocConfigProperties.isOverrideWithGenericResponse()
&& methodParameter.getExecutable().isAnnotationPresent(ExceptionHandler.class)) {
// ExceptionHandler's exception class resolution is non-trivial
// more info on its javadoc
ExceptionHandler exceptionHandler = methodParameter.getExecutable().getAnnotation(ExceptionHandler.class);
Set<Class<?>> exceptions = new HashSet<>();
if (exceptionHandler.value().length == 0) {
for (Parameter parameter : methodParameter.getExecutable().getParameters()) {
if (Throwable.class.isAssignableFrom(parameter.getType())) {
exceptions.add(parameter.getType());
}
}
}
else {
exceptions.addAll(asList(exceptionHandler.value()));
}
apiResponse.addExtension(EXTENSION_EXCEPTION_CLASSES, exceptions);
}
apiResponsesOp.addApiResponse(httpCode, apiResponse);
}
/**
* Sets description.
*
* @param httpCode the http code
* @param apiResponse the api response
*/
public static void setDescription(String httpCode, ApiResponse apiResponse) {
try {
HttpStatus httpStatus = HttpStatus.valueOf(Integer.parseInt(httpCode));
apiResponse.setDescription(httpStatus.getReasonPhrase());
}
catch (IllegalArgumentException e) {
apiResponse.setDescription(DEFAULT_DESCRIPTION);
}
}
/**
* Evaluate response status string.
*
* @param method the method
* @param beanType the bean type
* @param isGeneric the is generic
* @return the string
*/
public String evaluateResponseStatus(Method method, Class<?> beanType, boolean isGeneric) {
String responseStatus = null;
ResponseStatus annotation = AnnotatedElementUtils.findMergedAnnotation(method, ResponseStatus.class);
if (annotation == null && beanType != null)
annotation = AnnotatedElementUtils.findMergedAnnotation(beanType, ResponseStatus.class);
if (annotation != null)
responseStatus = String.valueOf(annotation.code().value());
if (annotation == null && !isGeneric)
responseStatus = String.valueOf(HttpStatus.OK.value());
return responseStatus;
}
/**
* Is void boolean.
*
* @param returnType the return type
* @return the boolean
*/
private boolean isVoid(Type returnType) {
boolean result = false;
if (Void.TYPE.equals(returnType) || Void.class.equals(returnType))
result = true;
else if (returnType instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) returnType).getActualTypeArguments();
if (types != null && isResponseTypeWrapper(ResolvableType.forType(returnType).getRawClass()))
result = isVoid(types[0]);
}
return result;
}
/**
* Gets generic map response.
*
* @param beanType the bean type
* @return the generic map response
*/
private synchronized Map<String, ApiResponse> getGenericMapResponse(Class<?> beanType) {
return controllerAdviceInfos.stream()
.filter(controllerAdviceInfo -> new ControllerAdviceBean(controllerAdviceInfo.getControllerAdvice()).isApplicableToBeanType(beanType))
.map(ControllerAdviceInfo::getApiResponseMap)
.collect(LinkedHashMap::new, Map::putAll, Map::putAll);
}
/**
* Is valid http code boolean.
*
* @param httpCode the http code
* @param methodParameter the method parameter
* @return the boolean
*/
private boolean isValidHttpCode(String httpCode, MethodParameter methodParameter) {
boolean result = false;
final Method method = methodParameter.getMethod();
if (method != null) {
Set<io.swagger.v3.oas.annotations.responses.ApiResponse> responseSet = getApiResponses(method);
if (isHttpCodePresent(httpCode, responseSet))
result = true;
else {
final io.swagger.v3.oas.annotations.Operation apiOperation = AnnotatedElementUtils.findMergedAnnotation(method,
io.swagger.v3.oas.annotations.Operation.class);
if (apiOperation != null) {
responseSet = new HashSet<>(Arrays.asList(apiOperation.responses()));
if (isHttpCodePresent(httpCode, responseSet))
result = true;
}
else if (httpCode.equals(evaluateResponseStatus(method, method.getClass(), false)))
result = true;
}
}
return result;
}
/**
* Is http code present boolean.
*
* @param httpCode the http code
* @param responseSet the response set
* @return the boolean
*/
private boolean isHttpCodePresent(String httpCode, Set<io.swagger.v3.oas.annotations.responses.ApiResponse> responseSet) {
return !responseSet.isEmpty() && responseSet.stream().anyMatch(apiResponseAnnotations -> httpCode.equals(apiResponseAnnotations.responseCode()));
}
/**
* Sets response entity exception handler class.
*
* @param responseEntityExceptionHandlerClass the response entity exception handler class
*/
public static void setResponseEntityExceptionHandlerClass(Class<?> responseEntityExceptionHandlerClass) {
GenericResponseService.responseEntityExceptionHandlerClass = responseEntityExceptionHandlerClass;
}
private ApiResponse cloneApiResponse(ApiResponse original) {
ApiResponse clone = new ApiResponse();
clone.set$ref(original.get$ref());
clone.setDescription(original.getDescription());
clone.setContent(original.getContent());
clone.setHeaders(original.getHeaders() == null ? null : new HashMap<>(original.getHeaders()));
clone.setExtensions(original.getExtensions() == null ? null : new HashMap<>(original.getExtensions()));
clone.setLinks(original.getLinks() == null ? null : new HashMap<>(original.getLinks()));
return clone;
}
}