forked from springdoc/springdoc-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractOpenApiResource.java
1330 lines (1226 loc) · 52.5 KB
/
AbstractOpenApiResource.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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* *
* * *
* * * * 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.api;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
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.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature;
import io.swagger.v3.core.filter.SpecFilter;
import io.swagger.v3.core.util.ReflectionUtils;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.callbacks.Callback;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.AbstractRequestService;
import org.springdoc.core.GenericParameterService;
import org.springdoc.core.GenericResponseService;
import org.springdoc.core.MethodAttributes;
import org.springdoc.core.OpenAPIService;
import org.springdoc.core.OperationService;
import org.springdoc.core.SpringDocConfigProperties;
import org.springdoc.core.SpringDocConfigProperties.ApiDocs.OpenApiVersion;
import org.springdoc.core.SpringDocConfigProperties.GroupConfig;
import org.springdoc.core.SpringDocProviders;
import org.springdoc.core.annotations.RouterOperations;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springdoc.core.customizers.OpenApiLocaleCustomizer;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.filters.OpenApiMethodFilter;
import org.springdoc.core.fn.AbstractRouterFunctionVisitor;
import org.springdoc.core.fn.RouterFunctionData;
import org.springdoc.core.fn.RouterOperation;
import org.springdoc.core.providers.ActuatorProvider;
import org.springdoc.core.providers.CloudFunctionProvider;
import org.springdoc.core.providers.JavadocProvider;
import org.springdoc.core.providers.ObjectMapperProvider;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import static org.springdoc.core.Constants.ACTUATOR_DEFAULT_GROUP;
import static org.springdoc.core.Constants.DOT;
import static org.springdoc.core.Constants.LINKS_SCHEMA_CUSTOMISER;
import static org.springdoc.core.Constants.OPERATION_ATTRIBUTE;
import static org.springdoc.core.Constants.SPRING_MVC_SERVLET_PATH;
import static org.springdoc.core.converters.SchemaPropertyDeprecatingConverter.isDeprecated;
import static org.springframework.util.AntPathMatcher.DEFAULT_PATH_SEPARATOR;
/**
* The type Abstract open api resource.
* @author bnasslahsen
* @author kevinraddatz
*/
public abstract class AbstractOpenApiResource extends SpecFilter {
/**
* The constant LOGGER.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractOpenApiResource.class);
/**
* The constant ADDITIONAL_REST_CONTROLLERS.
*/
private static final Set<Class<?>> ADDITIONAL_REST_CONTROLLERS = new CopyOnWriteArraySet<>();
/**
* The constant HIDDEN_REST_CONTROLLERS.
*/
private static final Set<Class<?>> HIDDEN_REST_CONTROLLERS = new CopyOnWriteArraySet<>();
/**
* The Open api builder.
*/
protected OpenAPIService openAPIService;
/**
* The open api builder object factory.
*/
private final ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory;
/**
* The Spring doc config properties.
*/
protected final SpringDocConfigProperties springDocConfigProperties;
/**
* The Request builder.
*/
private final AbstractRequestService requestBuilder;
/**
* The Response builder.
*/
private final GenericResponseService responseBuilder;
/**
* The Operation parser.
*/
private final OperationService operationParser;
/**
* The Open api customisers.
*/
private final Optional<List<OpenApiCustomiser>> openApiCustomisers;
/**
* The Operation customizers.
*/
private final Optional<List<OperationCustomizer>> operationCustomizers;
/**
* The method filters to use.
*/
private final Optional<List<OpenApiMethodFilter>> methodFilters;
/**
* The Ant path matcher.
*/
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* The Group name.
*/
protected final String groupName;
/**
* The constant MODEL_AND_VIEW_CLASS.
*/
private static Class<?> modelAndViewClass;
/**
* The OpenApi with locale customizers.
*/
private final Map<String, OpenApiLocaleCustomizer> openApiLocaleCustomizers;
/**
* The Spring doc providers.
*/
protected final SpringDocProviders springDocProviders;
/**
* Instantiates a new Abstract open api resource.
* @param groupName the group name
* @param openAPIBuilderObjectFactory the open api builder object factory
* @param requestBuilder the request builder
* @param responseBuilder the response builder
* @param operationParser the operation parser
* @param operationCustomizers the operation customizers
* @param openApiCustomisers the open api customisers
* @param methodFilters the method filters
* @param springDocConfigProperties the spring doc config properties
* @param springDocProviders the spring doc providers
*/
protected AbstractOpenApiResource(String groupName, ObjectFactory<OpenAPIService> openAPIBuilderObjectFactory,
AbstractRequestService requestBuilder,
GenericResponseService responseBuilder, OperationService operationParser,
Optional<List<OperationCustomizer>> operationCustomizers,
Optional<List<OpenApiCustomiser>> openApiCustomisers,
Optional<List<OpenApiMethodFilter>> methodFilters,
SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders) {
super();
this.groupName = Objects.requireNonNull(groupName, "groupName");
this.openAPIBuilderObjectFactory = openAPIBuilderObjectFactory;
this.openAPIService = openAPIBuilderObjectFactory.getObject();
this.requestBuilder = requestBuilder;
this.responseBuilder = responseBuilder;
this.operationParser = operationParser;
this.openApiCustomisers = openApiCustomisers;
this.methodFilters = methodFilters;
this.springDocProviders = springDocProviders;
//add the default customizers
Map<String, OpenApiCustomiser> existingOpenApiCustomisers = openAPIService.getContext().getBeansOfType(OpenApiCustomiser.class);
if (!CollectionUtils.isEmpty(existingOpenApiCustomisers) && existingOpenApiCustomisers.containsKey(LINKS_SCHEMA_CUSTOMISER))
openApiCustomisers.ifPresent(openApiCustomisersList -> openApiCustomisersList.add(existingOpenApiCustomisers.get(LINKS_SCHEMA_CUSTOMISER)));
this.springDocConfigProperties = springDocConfigProperties;
operationCustomizers.ifPresent(customizers -> customizers.removeIf(Objects::isNull));
this.operationCustomizers = operationCustomizers;
if (springDocConfigProperties.isPreLoadingEnabled())
Executors.newSingleThreadExecutor().execute(this::getOpenApi);
this.openApiLocaleCustomizers = openAPIService.getContext().getBeansOfType(OpenApiLocaleCustomizer.class);
}
/**
* Gets open api.
*/
private void getOpenApi() {
this.getOpenApi(Locale.getDefault());
}
/**
* Add rest controllers.
*
* @param classes the classes
*/
public static void addRestControllers(Class<?>... classes) {
ADDITIONAL_REST_CONTROLLERS.addAll(Arrays.asList(classes));
}
/**
* Add hidden rest controllers.
*
* @param classes the classes
*/
public static void addHiddenRestControllers(Class<?>... classes) {
HIDDEN_REST_CONTROLLERS.addAll(Arrays.asList(classes));
}
/**
* Add hidden rest controllers.
*
* @param classes the classes
*/
public static void addHiddenRestControllers(String... classes) {
Set<Class<?>> hiddenClasses = new HashSet<>();
for (String aClass : classes) {
try {
hiddenClasses.add(Class.forName(aClass));
}
catch (ClassNotFoundException e) {
LOGGER.warn("The following class doesn't exist and cannot be hidden: {}", aClass);
}
}
HIDDEN_REST_CONTROLLERS.addAll(hiddenClasses);
}
/**
* Gets open api.
* @param locale the locale
* @return the open api
*/
protected synchronized OpenAPI getOpenApi(Locale locale) {
OpenAPI openAPI;
final Locale finalLocale = locale == null ? Locale.getDefault() : locale;
if (openAPIService.getCachedOpenAPI(finalLocale) == null || springDocConfigProperties.isCacheDisabled()) {
Instant start = Instant.now();
openAPI = openAPIService.build(finalLocale);
Map<String, Object> mappingsMap = openAPIService.getMappingsMap().entrySet().stream()
.filter(controller -> (AnnotationUtils.findAnnotation(controller.getValue().getClass(),
Hidden.class) == null))
.filter(controller -> !AbstractOpenApiResource.isHiddenRestControllers(controller.getValue().getClass()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1));
Map<String, Object> findControllerAdvice = openAPIService.getControllerAdviceMap();
if (OpenApiVersion.OPENAPI_3_1 == springDocConfigProperties.getApiDocs().getVersion())
openAPI.openapi(OpenApiVersion.OPENAPI_3_1.getVersion());
if (springDocConfigProperties.isDefaultOverrideWithGenericResponse()) {
if (!CollectionUtils.isEmpty(mappingsMap))
findControllerAdvice.putAll(mappingsMap);
responseBuilder.buildGenericResponse(openAPI.getComponents(), findControllerAdvice, finalLocale);
}
getPaths(mappingsMap, finalLocale, openAPI);
Optional<CloudFunctionProvider> cloudFunctionProviderOptional = springDocProviders.getSpringCloudFunctionProvider();
cloudFunctionProviderOptional.ifPresent(cloudFunctionProvider -> {
List<RouterOperation> routerOperationList = cloudFunctionProvider.getRouterOperations(openAPI);
if (!CollectionUtils.isEmpty(routerOperationList))
this.calculatePath(routerOperationList, locale, openAPI);
}
);
if (!CollectionUtils.isEmpty(openAPI.getServers()))
openAPIService.setServersPresent(true);
openAPIService.updateServers(openAPI);
if (springDocConfigProperties.isRemoveBrokenReferenceDefinitions())
this.removeBrokenReferenceDefinitions(openAPI);
// run the optional customisers
List<Server> servers = openAPI.getServers();
List<Server> serversCopy = null;
try {
serversCopy = springDocProviders.jsonMapper()
.readValue(springDocProviders.jsonMapper().writeValueAsString(servers), new TypeReference<List<Server>>() {});
}
catch (JsonProcessingException e) {
LOGGER.warn("Json Processing Exception occurred: {}", e.getMessage());
}
openApiLocaleCustomizers.values().forEach(openApiLocaleCustomizer -> openApiLocaleCustomizer.customise(openAPI, finalLocale));
openApiCustomisers.ifPresent(apiCustomisers -> apiCustomisers.forEach(openApiCustomiser -> openApiCustomiser.customise(openAPI)));
if (!CollectionUtils.isEmpty(openAPI.getServers()) && !openAPI.getServers().equals(serversCopy))
openAPIService.setServersPresent(true);
openAPIService.setCachedOpenAPI(openAPI, finalLocale);
LOGGER.info("Init duration for springdoc-openapi is: {} ms",
Duration.between(start, Instant.now()).toMillis());
}
else {
LOGGER.debug("Fetching openApi document from cache");
openAPI = openAPIService.updateServers(openAPIService.getCachedOpenAPI(finalLocale));
}
return openAPI;
}
/**
* Gets paths.
*
* @param findRestControllers the find rest controllers
* @param locale the locale
* @param openAPI the open api
*/
protected abstract void getPaths(Map<String, Object> findRestControllers, Locale locale, OpenAPI openAPI);
/**
* Calculate path.
*
* @param handlerMethod the handler method
* @param routerOperation the router operation
* @param locale the locale
* @param openAPI the open api
*/
protected void calculatePath(HandlerMethod handlerMethod,
RouterOperation routerOperation, Locale locale, OpenAPI openAPI) {
String operationPath = routerOperation.getPath();
Set<RequestMethod> requestMethods = new HashSet<>(Arrays.asList(routerOperation.getMethods()));
io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation();
String[] methodConsumes = routerOperation.getConsumes();
String[] methodProduces = routerOperation.getProduces();
String[] headers = routerOperation.getHeaders();
Map<String, String> queryParams = routerOperation.getQueryParams();
Components components = openAPI.getComponents();
Paths paths = openAPI.getPaths();
Map<HttpMethod, Operation> operationMap = null;
if (paths.containsKey(operationPath)) {
PathItem pathItem = paths.get(operationPath);
operationMap = pathItem.readOperationsMap();
}
JavadocProvider javadocProvider = operationParser.getJavadocProvider();
for (RequestMethod requestMethod : requestMethods) {
Operation existingOperation = getExistingOperation(operationMap, requestMethod);
Method method = handlerMethod.getMethod();
// skip hidden operations
if (operationParser.isHidden(method))
continue;
RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(),
RequestMapping.class);
MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers, locale);
methodAttributes.setMethodOverloaded(existingOperation != null);
//Use the javadoc return if present
if (javadocProvider != null) {
methodAttributes.setJavadocReturn(javadocProvider.getMethodJavadocReturn(handlerMethod.getMethod()));
}
if (reqMappingClass != null) {
methodAttributes.setClassConsumes(reqMappingClass.consumes());
methodAttributes.setClassProduces(reqMappingClass.produces());
}
methodAttributes.calculateHeadersForClass(method.getDeclaringClass());
methodAttributes.calculateConsumesProduces(method);
Operation operation = (existingOperation != null) ? existingOperation : new Operation();
if (isDeprecated(method))
operation.setDeprecated(true);
// Add documentation from operation annotation
if (apiOperation == null || StringUtils.isBlank(apiOperation.operationId()))
apiOperation = AnnotatedElementUtils.findMergedAnnotation(method,
io.swagger.v3.oas.annotations.Operation.class);
calculateJsonView(apiOperation, methodAttributes, method);
if (apiOperation != null)
openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes);
fillParametersList(operation, queryParams, methodAttributes);
// compute tags
operation = openAPIService.buildTags(handlerMethod, operation, openAPI, locale);
io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyDoc = AnnotatedElementUtils.findMergedAnnotation(method,
io.swagger.v3.oas.annotations.parameters.RequestBody.class);
// RequestBody in Operation
requestBuilder.getRequestBodyBuilder()
.buildRequestBodyFromDoc(requestBodyDoc, methodAttributes, components,
methodAttributes.getJsonViewAnnotationForRequestBody())
.ifPresent(operation::setRequestBody);
// requests
operation = requestBuilder.build(handlerMethod, requestMethod, operation, methodAttributes, openAPI);
// responses
ApiResponses apiResponses = responseBuilder.build(components, handlerMethod, operation, methodAttributes);
operation.setResponses(apiResponses);
// get javadoc method description
if (javadocProvider != null) {
String description = javadocProvider.getMethodJavadocDescription(handlerMethod.getMethod());
String summary = javadocProvider.getFirstSentence(description);
boolean emptyOverrideDescription = StringUtils.isEmpty(operation.getDescription());
boolean emptyOverrideSummary = StringUtils.isEmpty(operation.getSummary());
if (!StringUtils.isEmpty(description) && emptyOverrideDescription) {
operation.setDescription(description);
}
// if there is a previously set description
// but no summary then it is intentional
// we keep it as is
if (!StringUtils.isEmpty(summary) && emptyOverrideSummary && emptyOverrideDescription) {
operation.setSummary(javadocProvider.getFirstSentence(description));
}
}
Set<io.swagger.v3.oas.annotations.callbacks.Callback> apiCallbacks = AnnotatedElementUtils.findMergedRepeatableAnnotations(method, io.swagger.v3.oas.annotations.callbacks.Callback.class);
// callbacks
buildCallbacks(openAPI, methodAttributes, operation, apiCallbacks);
// allow for customisation
operation = customiseOperation(operation, handlerMethod);
PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths);
paths.addPathItem(operationPath, pathItemObject);
}
}
/**
* Build callbacks.
*
* @param openAPI the open api
* @param methodAttributes the method attributes
* @param operation the operation
* @param apiCallbacks the api callbacks
*/
private void buildCallbacks(OpenAPI openAPI, MethodAttributes methodAttributes, Operation operation, Set<Callback> apiCallbacks) {
if (!CollectionUtils.isEmpty(apiCallbacks))
operationParser.buildCallbacks(apiCallbacks, openAPI, methodAttributes)
.ifPresent(operation::setCallbacks);
}
/**
* Calculate path.
*
* @param routerOperationList the router operation list
* @param locale the locale
* @param openAPI the open api
*/
protected void calculatePath(List<RouterOperation> routerOperationList, Locale locale, OpenAPI openAPI) {
ApplicationContext applicationContext = openAPIService.getContext();
if (!CollectionUtils.isEmpty(routerOperationList)) {
Collections.sort(routerOperationList);
for (RouterOperation routerOperation : routerOperationList) {
if (routerOperation.getBeanClass() != null && !Void.class.equals(routerOperation.getBeanClass())) {
Object handlerBean = applicationContext.getBean(routerOperation.getBeanClass());
HandlerMethod handlerMethod = null;
if (StringUtils.isNotBlank(routerOperation.getBeanMethod())) {
try {
if (ArrayUtils.isEmpty(routerOperation.getParameterTypes())) {
Method[] declaredMethods = AopUtils.getTargetClass(handlerBean).getDeclaredMethods();
Optional<Method> methodOptional = Arrays.stream(declaredMethods)
.filter(method -> routerOperation.getBeanMethod().equals(method.getName()) && method.getParameters().length == 0)
.findAny();
if (!methodOptional.isPresent())
methodOptional = Arrays.stream(declaredMethods)
.filter(method1 -> routerOperation.getBeanMethod().equals(method1.getName()))
.findAny();
if (methodOptional.isPresent())
handlerMethod = new HandlerMethod(handlerBean, methodOptional.get());
}
else
handlerMethod = new HandlerMethod(handlerBean, routerOperation.getBeanMethod(), routerOperation.getParameterTypes());
}
catch (NoSuchMethodException e) {
LOGGER.error(e.getMessage());
}
if (handlerMethod != null && isFilterCondition(handlerMethod, routerOperation.getPath(), routerOperation.getProduces(), routerOperation.getConsumes(), routerOperation.getHeaders()))
calculatePath(handlerMethod, routerOperation, locale, openAPI);
}
}
else if (routerOperation.getOperation() != null && StringUtils.isNotBlank(routerOperation.getOperation().operationId()) && isFilterCondition(routerOperation.getPath(), routerOperation.getProduces(), routerOperation.getConsumes(), routerOperation.getHeaders())) {
calculatePath(routerOperation, locale, openAPI);
}
else if (routerOperation.getOperationModel() != null && StringUtils.isNotBlank(routerOperation.getOperationModel().getOperationId()) && isFilterCondition(routerOperation.getPath(), routerOperation.getProduces(), routerOperation.getConsumes(), routerOperation.getHeaders())) {
calculatePath(routerOperation, locale, openAPI);
}
}
}
}
/**
* Calculate path.
*
* @param routerOperation the router operation
* @param locale the locale
*/
protected void calculatePath(RouterOperation routerOperation, Locale locale, OpenAPI openAPI) {
String operationPath = routerOperation.getPath();
io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation();
String[] methodConsumes = routerOperation.getConsumes();
String[] methodProduces = routerOperation.getProduces();
String[] headers = routerOperation.getHeaders();
Map<String, String> queryParams = routerOperation.getQueryParams();
Paths paths = openAPI.getPaths();
Map<HttpMethod, Operation> operationMap = null;
if (paths.containsKey(operationPath)) {
PathItem pathItem = paths.get(operationPath);
operationMap = pathItem.readOperationsMap();
}
for (RequestMethod requestMethod : routerOperation.getMethods()) {
Operation existingOperation = getExistingOperation(operationMap, requestMethod);
MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers, locale);
methodAttributes.setMethodOverloaded(existingOperation != null);
Operation operation = getOperation(routerOperation, existingOperation);
if (apiOperation != null)
openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes);
String operationId = operationParser.getOperationId(operation.getOperationId(), openAPI);
operation.setOperationId(operationId);
fillParametersList(operation, queryParams, methodAttributes);
if (!CollectionUtils.isEmpty(operation.getParameters()))
operation.getParameters().stream()
.filter(parameter -> StringUtils.isEmpty(parameter.get$ref()))
.forEach(parameter -> {
if (parameter.getSchema() == null)
parameter.setSchema(new StringSchema());
if (parameter.getIn() == null)
parameter.setIn(ParameterIn.QUERY.toString());
}
);
PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths);
paths.addPathItem(operationPath, pathItemObject);
}
}
/**
* Calculate path.
*
* @param handlerMethod the handler method
* @param operationPath the operation path
* @param requestMethods the request methods
* @param consumes the consumes
* @param produces the produces
* @param headers the headers
* @param locale the locale
* @param openAPI the open api
*/
protected void calculatePath(HandlerMethod handlerMethod, String operationPath,
Set<RequestMethod> requestMethods, String[] consumes, String[] produces, String[] headers, Locale locale, OpenAPI openAPI) {
this.calculatePath(handlerMethod, new RouterOperation(operationPath, requestMethods.toArray(new RequestMethod[requestMethods.size()]), consumes, produces, headers), locale, openAPI);
}
/**
* Gets router function paths.
*
* @param beanName the bean name
* @param routerFunctionVisitor the router function visitor
* @param locale the locale
* @param openAPI the open api
*/
protected void getRouterFunctionPaths(String beanName, AbstractRouterFunctionVisitor routerFunctionVisitor,
Locale locale, OpenAPI openAPI) {
boolean withRouterOperation = routerFunctionVisitor.getRouterFunctionDatas().stream()
.anyMatch(routerFunctionData -> routerFunctionData.getAttributes().containsKey(OPERATION_ATTRIBUTE));
if (withRouterOperation) {
List<RouterOperation> operationList = routerFunctionVisitor.getRouterFunctionDatas().stream().map(RouterOperation::new).collect(Collectors.toList());
calculatePath(operationList, locale, openAPI);
}
else {
List<org.springdoc.core.annotations.RouterOperation> routerOperationList = new ArrayList<>();
ApplicationContext applicationContext = openAPIService.getContext();
RouterOperations routerOperations = applicationContext.findAnnotationOnBean(beanName, RouterOperations.class);
if (routerOperations == null) {
org.springdoc.core.annotations.RouterOperation routerOperation = applicationContext.findAnnotationOnBean(beanName, org.springdoc.core.annotations.RouterOperation.class);
if (routerOperation != null)
routerOperationList.add(routerOperation);
}
else
routerOperationList.addAll(Arrays.asList(routerOperations.value()));
if (routerOperationList.size() == 1)
calculatePath(routerOperationList.stream().map(routerOperation -> new RouterOperation(routerOperation, routerFunctionVisitor.getRouterFunctionDatas().get(0))).collect(Collectors.toList()), locale, openAPI);
else {
List<RouterOperation> operationList = routerOperationList.stream().map(RouterOperation::new).collect(Collectors.toList());
mergeRouters(routerFunctionVisitor.getRouterFunctionDatas(), operationList);
calculatePath(operationList, locale, openAPI);
}
}
}
/**
* Is filter condition boolean.
*
* @param handlerMethod the handler method
* @param operationPath the operation path
* @param produces the produces
* @param consumes the consumes
* @param headers the headers
* @return the boolean
*/
protected boolean isFilterCondition(HandlerMethod handlerMethod, String operationPath, String[] produces, String[] consumes, String[] headers) {
return isMethodToFilter(handlerMethod)
&& isPackageToScan(handlerMethod.getBeanType().getPackage())
&& isFilterCondition(operationPath, produces, consumes, headers);
}
/**
* Is target method suitable for inclusion in current documentation/
*
* @param handlerMethod the method to check
* @return whether the method should be included in the current OpenAPI definition
*/
protected boolean isMethodToFilter(HandlerMethod handlerMethod) {
return this.methodFilters
.map(Collection::stream)
.map(stream -> stream.allMatch(m -> m.isMethodToInclude(handlerMethod.getMethod())))
.orElse(true);
}
/**
* Is condition to match boolean.
*
* @param existingConditions the existing conditions
* @param conditionType the condition type
* @return the boolean
*/
protected boolean isConditionToMatch(String[] existingConditions, ConditionType conditionType) {
List<String> conditionsToMatch = getConditionsToMatch(conditionType);
if (CollectionUtils.isEmpty(conditionsToMatch)) {
Optional<GroupConfig> optionalGroupConfig = springDocConfigProperties.getGroupConfigs().stream().filter(groupConfig -> this.groupName.equals(groupConfig.getGroup())).findAny();
if (optionalGroupConfig.isPresent())
conditionsToMatch = getConditionsToMatch(conditionType, optionalGroupConfig.get());
}
return CollectionUtils.isEmpty(conditionsToMatch)
|| (!ArrayUtils.isEmpty(existingConditions) && conditionsToMatch.size() == existingConditions.length && conditionsToMatch.containsAll(Arrays.asList(existingConditions)));
}
/**
* Is package to scan boolean.
*
* @param aPackage the a package
* @return the boolean
*/
protected boolean isPackageToScan(Package aPackage) {
if (aPackage == null)
return true;
final String packageName = aPackage.getName();
List<String> packagesToScan = springDocConfigProperties.getPackagesToScan();
List<String> packagesToExclude = springDocConfigProperties.getPackagesToExclude();
if (CollectionUtils.isEmpty(packagesToScan)) {
Optional<GroupConfig> optionalGroupConfig = springDocConfigProperties.getGroupConfigs().stream().filter(groupConfig -> this.groupName.equals(groupConfig.getGroup())).findAny();
if (optionalGroupConfig.isPresent())
packagesToScan = optionalGroupConfig.get().getPackagesToScan();
}
if (CollectionUtils.isEmpty(packagesToExclude)) {
Optional<GroupConfig> optionalGroupConfig = springDocConfigProperties.getGroupConfigs().stream().filter(groupConfig -> this.groupName.equals(groupConfig.getGroup())).findAny();
if (optionalGroupConfig.isPresent())
packagesToExclude = optionalGroupConfig.get().getPackagesToExclude();
}
boolean include = CollectionUtils.isEmpty(packagesToScan)
|| packagesToScan.stream().anyMatch(pack -> packageName.equals(pack)
|| packageName.startsWith(pack + DOT));
boolean exclude = !CollectionUtils.isEmpty(packagesToExclude)
&& (packagesToExclude.stream().anyMatch(pack -> packageName.equals(pack)
|| packageName.startsWith(pack + DOT)));
return include && !exclude;
}
/**
* Is path to match boolean.
*
* @param operationPath the operation path
* @return the boolean
*/
protected boolean isPathToMatch(String operationPath) {
List<String> pathsToMatch = springDocConfigProperties.getPathsToMatch();
List<String> pathsToExclude = springDocConfigProperties.getPathsToExclude();
if (CollectionUtils.isEmpty(pathsToMatch)) {
Optional<GroupConfig> optionalGroupConfig = springDocConfigProperties.getGroupConfigs().stream().filter(groupConfig -> this.groupName.equals(groupConfig.getGroup())).findAny();
if (optionalGroupConfig.isPresent())
pathsToMatch = optionalGroupConfig.get().getPathsToMatch();
}
if (CollectionUtils.isEmpty(pathsToExclude)) {
Optional<GroupConfig> optionalGroupConfig = springDocConfigProperties.getGroupConfigs().stream().filter(groupConfig -> this.groupName.equals(groupConfig.getGroup())).findAny();
if (optionalGroupConfig.isPresent())
pathsToExclude = optionalGroupConfig.get().getPathsToExclude();
}
boolean include = CollectionUtils.isEmpty(pathsToMatch) || pathsToMatch.stream().anyMatch(pattern -> antPathMatcher.match(pattern, operationPath));
boolean exclude = !CollectionUtils.isEmpty(pathsToExclude) && pathsToExclude.stream().anyMatch(pattern -> antPathMatcher.match(pattern, operationPath));
return include && !exclude;
}
/**
* Decode string.
*
* @param requestURI the request uri
* @return the string
*/
protected String decode(String requestURI) {
try {
return URLDecoder.decode(requestURI, StandardCharsets.UTF_8.toString());
}
catch (UnsupportedEncodingException e) {
return requestURI;
}
}
/**
* Is additional rest controller boolean.
*
* @param rawClass the raw class
* @return the boolean
*/
protected boolean isAdditionalRestController(Class<?> rawClass) {
return ADDITIONAL_REST_CONTROLLERS.stream().anyMatch(clazz -> clazz.isAssignableFrom(rawClass));
}
/**
* Contains response body boolean.
*
* @param handlerMethod the handler method
* @return the boolean
*/
public static boolean containsResponseBody(HandlerMethod handlerMethod) {
ResponseBody responseBodyAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), ResponseBody.class);
if (responseBodyAnnotation == null)
responseBodyAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), ResponseBody.class);
return responseBodyAnnotation != null;
}
/**
* Is rest controller boolean.
*
* @param restControllers the rest controllers
* @param handlerMethod the handler method
* @param operationPath the operation path
* @return the boolean
*/
protected boolean isRestController(Map<String, Object> restControllers, HandlerMethod handlerMethod,
String operationPath) {
boolean hasOperationAnnotation = AnnotatedElementUtils.hasAnnotation(handlerMethod.getMethod(), io.swagger.v3.oas.annotations.Operation.class);
return ((containsResponseBody(handlerMethod) || hasOperationAnnotation) && restControllers.containsKey(handlerMethod.getBean().toString()) || isAdditionalRestController(handlerMethod.getBeanType()))
&& operationPath.startsWith(DEFAULT_PATH_SEPARATOR)
&& (springDocConfigProperties.isModelAndViewAllowed() || modelAndViewClass == null || !modelAndViewClass.isAssignableFrom(handlerMethod.getMethod().getReturnType()));
}
/**
* Is hidden rest controllers boolean.
*
* @param rawClass the raw class
* @return the boolean
*/
public static boolean isHiddenRestControllers(Class<?> rawClass) {
return HIDDEN_REST_CONTROLLERS.stream().anyMatch(clazz -> clazz.isAssignableFrom(rawClass));
}
/**
* Gets default allowed http methods.
*
* @return the default allowed http methods
*/
protected Set<RequestMethod> getDefaultAllowedHttpMethods() {
RequestMethod[] allowedRequestMethods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS, RequestMethod.HEAD };
return new HashSet<>(Arrays.asList(allowedRequestMethods));
}
/**
* Customise operation operation.
*
* @param operation the operation
* @param handlerMethod the handler method
* @return the operation
*/
protected Operation customiseOperation(Operation operation, HandlerMethod handlerMethod) {
if (operationCustomizers.isPresent()) {
List<OperationCustomizer> operationCustomizerList = operationCustomizers.get();
for (OperationCustomizer operationCustomizer : operationCustomizerList)
operation = operationCustomizer.customize(operation, handlerMethod);
}
return operation;
}
/**
* Merge routers.
*
* @param routerFunctionDatas the router function datas
* @param routerOperationList the router operation list
*/
protected void mergeRouters(List<RouterFunctionData> routerFunctionDatas, List<RouterOperation> routerOperationList) {
for (RouterOperation routerOperation : routerOperationList) {
if (StringUtils.isNotBlank(routerOperation.getPath())) {
// PATH
List<RouterFunctionData> routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getMethods())) {
// PATH + METHOD
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualMethods(routerOperation.getMethods(), routerFunctionData1.getMethods()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getProduces())) {
// PATH + METHOD + PRODUCES
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualMethods(routerOperation.getMethods(), routerFunctionData1.getMethods())
&& isEqualArrays(routerFunctionData1.getProduces(), routerOperation.getProduces()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getConsumes())) {
// PATH + METHOD + PRODUCES + CONSUMES
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualMethods(routerOperation.getMethods(), routerFunctionData1.getMethods())
&& isEqualArrays(routerFunctionData1.getProduces(), routerOperation.getProduces())
&& isEqualArrays(routerFunctionData1.getConsumes(), routerOperation.getConsumes()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
}
}
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getConsumes())) {
// PATH + METHOD + CONSUMES
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualMethods(routerOperation.getMethods(), routerFunctionData1.getMethods())
&& isEqualArrays(routerFunctionData1.getConsumes(), routerOperation.getConsumes()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
}
}
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getProduces())) {
// PATH + PRODUCES
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualArrays(routerFunctionData1.getProduces(), routerOperation.getProduces()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getConsumes())) {
// PATH + PRODUCES + CONSUMES
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualMethods(routerOperation.getMethods(), routerFunctionData1.getMethods())
&& isEqualArrays(routerFunctionData1.getConsumes(), routerOperation.getConsumes())
&& isEqualArrays(routerFunctionData1.getProduces(), routerOperation.getProduces()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
}
}
else if (routerFunctionDataList.size() > 1 && ArrayUtils.isNotEmpty(routerOperation.getConsumes())) {
// PATH + CONSUMES
routerFunctionDataList = routerFunctionDatas.stream()
.filter(routerFunctionData1 -> routerFunctionData1.getPath().equals(routerOperation.getPath())
&& isEqualArrays(routerFunctionData1.getConsumes(), routerOperation.getConsumes()))
.collect(Collectors.toList());
if (routerFunctionDataList.size() == 1)
fillRouterOperation(routerFunctionDataList.get(0), routerOperation);
}
}
}
}
/**
* Calculate json view.
*
* @param apiOperation the api operation
* @param methodAttributes the method attributes
* @param method the method
*/
private void calculateJsonView(io.swagger.v3.oas.annotations.Operation apiOperation,
MethodAttributes methodAttributes, Method method) {
JsonView jsonViewAnnotation;
JsonView jsonViewAnnotationForRequestBody;
if (apiOperation != null && apiOperation.ignoreJsonView()) {
jsonViewAnnotation = null;
jsonViewAnnotationForRequestBody = null;
}
else {
jsonViewAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, JsonView.class);
/*
* If one and only one exists, use the @JsonView annotation from the method
* parameter annotated with @RequestBody. Otherwise fall back to the @JsonView
* annotation for the method itself.
*/
jsonViewAnnotationForRequestBody = (JsonView) Arrays.stream(ReflectionUtils.getParameterAnnotations(method))
.filter(arr -> Arrays.stream(arr)
.anyMatch(annotation -> (annotation.annotationType()
.equals(io.swagger.v3.oas.annotations.parameters.RequestBody.class) || annotation.annotationType().equals(RequestBody.class))))
.flatMap(Arrays::stream).filter(annotation -> annotation.annotationType().equals(JsonView.class))
.reduce((a, b) -> null).orElse(jsonViewAnnotation);
}
methodAttributes.setJsonViewAnnotation(jsonViewAnnotation);
methodAttributes.setJsonViewAnnotationForRequestBody(jsonViewAnnotationForRequestBody);
}
/**
* Is equal arrays boolean.
*
* @param array1 the array 1
* @param array2 the array 2
* @return the boolean
*/
private boolean isEqualArrays(String[] array1, String[] array2) {
Arrays.sort(array1);
Arrays.sort(array2);
return Arrays.equals(array1, array2);
}
/**
* Is equal methods boolean.
*
* @param requestMethods1 the request methods 1
* @param requestMethods2 the request methods 2
* @return the boolean
*/
private boolean isEqualMethods(RequestMethod[] requestMethods1, RequestMethod[] requestMethods2) {
Arrays.sort(requestMethods1);
Arrays.sort(requestMethods2);
return Arrays.equals(requestMethods1, requestMethods2);
}
/**