/
ApplicationProcessor.java
1049 lines (911 loc) · 46.3 KB
/
ApplicationProcessor.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
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) [2018-2019] Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package fish.payara.microprofile.openapi.impl.processor;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.WARNING;
import static java.util.logging.Level.SEVERE;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import org.eclipse.microprofile.openapi.annotations.ExternalDocumentation;
import org.eclipse.microprofile.openapi.annotations.OpenAPIDefinition;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.callbacks.Callback;
import org.eclipse.microprofile.openapi.annotations.callbacks.Callbacks;
import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
import org.eclipse.microprofile.openapi.annotations.extensions.Extension;
import org.eclipse.microprofile.openapi.annotations.extensions.Extensions;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement;
import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements;
import org.eclipse.microprofile.openapi.annotations.security.SecurityScheme;
import org.eclipse.microprofile.openapi.annotations.security.SecuritySchemes;
import org.eclipse.microprofile.openapi.annotations.servers.Server;
import org.eclipse.microprofile.openapi.annotations.servers.Servers;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.eclipse.microprofile.openapi.annotations.tags.Tags;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.PathItem;
import org.eclipse.microprofile.openapi.models.Reference;
import org.eclipse.microprofile.openapi.models.media.MediaType;
import org.eclipse.microprofile.openapi.models.media.Schema.SchemaType;
import org.eclipse.microprofile.openapi.models.parameters.Parameter.In;
import fish.payara.microprofile.openapi.api.processor.OASProcessor;
import fish.payara.microprofile.openapi.api.visitor.ApiContext;
import fish.payara.microprofile.openapi.api.visitor.ApiVisitor;
import fish.payara.microprofile.openapi.api.visitor.ApiWalker;
import fish.payara.microprofile.openapi.impl.config.OpenApiConfiguration;
import fish.payara.microprofile.openapi.impl.model.ExtensibleImpl;
import fish.payara.microprofile.openapi.impl.model.ExternalDocumentationImpl;
import fish.payara.microprofile.openapi.impl.model.OpenAPIImpl;
import fish.payara.microprofile.openapi.impl.model.OperationImpl;
import fish.payara.microprofile.openapi.impl.model.PathItemImpl;
import fish.payara.microprofile.openapi.impl.model.callbacks.CallbackImpl;
import fish.payara.microprofile.openapi.impl.model.media.ContentImpl;
import fish.payara.microprofile.openapi.impl.model.media.MediaTypeImpl;
import fish.payara.microprofile.openapi.impl.model.media.SchemaImpl;
import fish.payara.microprofile.openapi.impl.model.parameters.ParameterImpl;
import fish.payara.microprofile.openapi.impl.model.parameters.RequestBodyImpl;
import fish.payara.microprofile.openapi.impl.model.responses.APIResponseImpl;
import fish.payara.microprofile.openapi.impl.model.responses.APIResponsesImpl;
import fish.payara.microprofile.openapi.impl.model.security.SecurityRequirementImpl;
import fish.payara.microprofile.openapi.impl.model.security.SecuritySchemeImpl;
import fish.payara.microprofile.openapi.impl.model.servers.ServerImpl;
import fish.payara.microprofile.openapi.impl.model.tags.TagImpl;
import fish.payara.microprofile.openapi.impl.model.util.AnnotationInfo;
import fish.payara.microprofile.openapi.impl.model.util.ModelUtils;
import fish.payara.microprofile.openapi.impl.visitor.OpenApiWalker;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.eclipse.microprofile.openapi.models.parameters.Parameter.Style;
/**
* A processor to parse the application for annotations, to add to the OpenAPI
* model.
*/
public class ApplicationProcessor implements OASProcessor, ApiVisitor {
private static final Logger LOGGER = Logger.getLogger(ApplicationProcessor.class.getName());
/**
* A list of all classes in the given application.
*/
private final Set<Class<?>> classes;
/**
* @param appClassLoader the class loader for the application.
*/
public ApplicationProcessor(Set<Class<?>> appClasses) {
this.classes = appClasses;
this.classes.removeIf(cls -> cls.isInterface() || Modifier.isAbstract(cls.getModifiers()));
}
@Override
public OpenAPI process(OpenAPI api, OpenApiConfiguration config) {
if (config == null || !config.getScanDisable()) {
ApiWalker apiWalker = new OpenApiWalker(api, config == null ? classes : config.getValidClasses(classes));
apiWalker.accept(this);
}
return api;
}
// JAX-RS method handlers
@Override
public void visitGET(GET get, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setGET(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitPOST(POST post, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setPOST(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitPUT(PUT put, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setPUT(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitDELETE(DELETE delete, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setDELETE(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitHEAD(HEAD head, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setHEAD(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitOPTIONS(OPTIONS options, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setOPTIONS(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitPATCH(PATCH patch, Method element, ApiContext context) {
if (context.getPath() == null) {
return;
}
// Get or create the path item
PathItem pathItem = context.getApi().getPaths().getOrDefault(context.getPath(), new PathItemImpl());
context.getApi().getPaths().addPathItem(context.getPath(), pathItem);
org.eclipse.microprofile.openapi.models.Operation operation = new OperationImpl();
pathItem.setPATCH(operation);
operation.setOperationId(element.getName());
// Add the default request
insertDefaultRequestBody(context, operation, element);
// Add the default response
insertDefaultResponse(context, operation, element);
}
@Override
public void visitProduces(Produces produces, AnnotatedElement element, ApiContext context) {
if (element instanceof Method && context.getWorkingOperation() != null) {
for (org.eclipse.microprofile.openapi.models.responses.APIResponse response : context.getWorkingOperation()
.getResponses().values()) {
if (response != null) {
// Find the wildcard return type
if (response.getContent() != null
&& response.getContent().getMediaType(javax.ws.rs.core.MediaType.WILDCARD) != null) {
MediaType wildcardMedia = response.getContent().getMediaType(javax.ws.rs.core.MediaType.WILDCARD);
// Copy the wildcard return type to the valid response types
for (String mediaType : produces.value()) {
response.getContent().addMediaType(getContentType(mediaType), wildcardMedia);
}
// If there is an @Produces, remove the wildcard
response.getContent().removeMediaType(javax.ws.rs.core.MediaType.WILDCARD);
}
}
}
}
}
@Override
public void visitConsumes(Consumes consumes, AnnotatedElement element, ApiContext context) {
if (element instanceof Method && context.getWorkingOperation() != null) {
org.eclipse.microprofile.openapi.models.parameters.RequestBody requestBody = context.getWorkingOperation()
.getRequestBody();
if (requestBody != null) {
// Find the wildcard return type
if (requestBody.getContent() != null
&& requestBody.getContent().getMediaType(javax.ws.rs.core.MediaType.WILDCARD) != null) {
MediaType wildcardMedia = requestBody.getContent().getMediaType(javax.ws.rs.core.MediaType.WILDCARD);
// Copy the wildcard return type to the valid request body types
for (String mediaType : consumes.value()) {
requestBody.getContent().addMediaType(getContentType(mediaType), wildcardMedia);
}
// If there is an @Consumes, remove the wildcard
requestBody.getContent().removeMediaType(javax.ws.rs.core.MediaType.WILDCARD);
}
}
}
}
@Override
public void visitQueryParam(QueryParam param, AnnotatedElement element, ApiContext context) {
addParameter(element, context, param.value(), In.QUERY, null);
}
@Override
public void visitPathParam(PathParam param, AnnotatedElement element, ApiContext context) {
addParameter(element, context, param.value(), In.PATH, true);
}
@Override
public void visitFormParam(FormParam param, AnnotatedElement element, ApiContext context) {
// Find the aggregate schema type of all the parameters
SchemaType formSchemaType = null;
if (element instanceof java.lang.reflect.Parameter) {
java.lang.reflect.Parameter[] parameters = ((java.lang.reflect.Parameter) element)
.getDeclaringExecutable().getParameters();
for (java.lang.reflect.Parameter methodParam : parameters) {
if (methodParam.isAnnotationPresent(FormParam.class)) {
formSchemaType = ModelUtils.getParentSchemaType(formSchemaType,
ModelUtils.getSchemaType(methodParam.getType()));
}
}
}
if (context.getWorkingOperation() != null) {
// If there's no request body, fill out a new one right down to the schema
if (context.getWorkingOperation().getRequestBody() == null) {
context.getWorkingOperation().setRequestBody(new RequestBodyImpl().content(new ContentImpl()
.addMediaType(javax.ws.rs.core.MediaType.WILDCARD, new MediaTypeImpl()
.schema(new SchemaImpl()))));
}
// Set the request body type accordingly.
context.getWorkingOperation().getRequestBody().getContent()
.getMediaType(javax.ws.rs.core.MediaType.WILDCARD).getSchema()
.setType(formSchemaType);
}
}
@Override
public void visitHeaderParam(HeaderParam param, AnnotatedElement element, ApiContext context) {
addParameter(element, context, param.value(), In.HEADER, null);
}
@Override
public void visitCookieParam(CookieParam param, AnnotatedElement element, ApiContext context) {
addParameter(element, context, param.value(), In.COOKIE, null);
}
private static void addParameter(AnnotatedElement element, ApiContext context, String name, In in, Boolean required) {
org.eclipse.microprofile.openapi.models.parameters.Parameter newParameter = new ParameterImpl();
newParameter.setName(name);
newParameter.setIn(in);
newParameter.setStyle(Style.SIMPLE);
newParameter.setRequired(required);
SchemaImpl schema = new SchemaImpl();
String defaultValue = getDefaultValueIfPresent(element);
if (element instanceof java.lang.reflect.Parameter) {
java.lang.reflect.Parameter parameter = (java.lang.reflect.Parameter) element;
schema.setType(ModelUtils.getSchemaType(parameter.getType()));
} else {
Field field = (Field) element;
schema.setType(ModelUtils.getSchemaType(field.getType()));
}
if (schema.getType() == SchemaType.ARRAY) {
schema.setItems(getArraySchema(element));
if (defaultValue != null) {
schema.getItems().setDefaultValue(defaultValue);
}
} else if (defaultValue != null) {
schema.setDefaultValue(defaultValue);
}
newParameter.setSchema(schema);
if (context.getWorkingOperation() != null) {
context.getWorkingOperation().addParameter(newParameter);
} else {
LOGGER.log(SEVERE, "Couldn't add " + newParameter.getIn() + " parameter, \"" + newParameter.getName()
+ "\" to the OpenAPI Document. This is usually caused by declaring parameter under a method with "
+ "an unsupported annotation.");
}
}
private static SchemaImpl getArraySchema(AnnotatedElement element) {
SchemaImpl arraySchema = new SchemaImpl();
ParameterizedType parameterizedType;
if (element instanceof java.lang.reflect.Parameter) {
java.lang.reflect.Parameter parameter = (java.lang.reflect.Parameter) element;
parameterizedType = (ParameterizedType) parameter.getParameterizedType();
} else {
Field field = (Field) element;
parameterizedType = (ParameterizedType) field.getAnnotatedType().getType();
}
arraySchema.setType(ModelUtils.getSchemaType((Class<?>) parameterizedType.getActualTypeArguments()[0]));
return arraySchema;
}
private static String getDefaultValueIfPresent(AnnotatedElement element) {
Annotation[] annotations = element.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if ("javax.ws.rs.DefaultValue".equals(annotation.annotationType().getName())) {
try {
return (String) annotation.annotationType().getMethod("value").invoke(annotation);
} catch (Exception ex) {
LOGGER.log(WARNING, "Couldn't get the default value", ex);
}
}
}
return null;
}
@Override
public void visitOpenAPI(OpenAPIDefinition definition, AnnotatedElement element, ApiContext context) {
OpenAPIImpl.merge(definition, context.getApi(), true);
}
@Override
public void visitSchema(Schema schema, AnnotatedElement element, ApiContext context) {
if (element instanceof Class) {
if (((Class) element).isEnum()) {
vistEnumClass(schema, (Class<?>) element, context);
} else {
visitSchemaClass(schema, (Class<?>) element, context);
}
}
if (element instanceof Field) {
visitSchemaField(schema, (Field) element, context);
}
if (element instanceof java.lang.reflect.Parameter) {
visitSchemaParameter(schema, (java.lang.reflect.Parameter) element, context);
}
}
private void vistEnumClass(Schema schema, Class<?> clazz, ApiContext context) {
// Get the schema object name
String schemaName = (schema == null) ? null : schema.name();
if (schemaName == null || schemaName.isEmpty()) {
schemaName = clazz.getSimpleName();
}
org.eclipse.microprofile.openapi.models.media.Schema newSchema = new SchemaImpl();
context.getApi().getComponents().addSchema(schemaName, newSchema);
if (schema != null) {
SchemaImpl.merge(schema, newSchema, true, context.getApi().getComponents().getSchemas());
}
if (schema == null || schema.enumeration().length == 0) {
//if the schema annotation does not specify enums, then all enum fields will be added
for (Object enumField : clazz.getEnumConstants()) {
newSchema.addEnumeration(enumField);
}
}
}
private void visitSchemaClass(Schema schema, Class<?> clazz, ApiContext context) {
// Get the schema object name
String schemaName = (schema == null) ? null : schema.name();
if (schemaName == null || schemaName.isEmpty()) {
schemaName = clazz.getSimpleName();
}
// Add a new schema
org.eclipse.microprofile.openapi.models.media.Schema newSchema = new SchemaImpl();
context.getApi().getComponents().addSchema(schemaName, newSchema);
// If there is an annotation
if (schema != null) {
SchemaImpl.merge(schema, newSchema, true, context.getApi().getComponents().getSchemas());
} else {
newSchema.setType(SchemaType.OBJECT);
Map<String, org.eclipse.microprofile.openapi.models.media.Schema> fields = new LinkedHashMap<>();
for (Field field : clazz.getDeclaredFields()) {
if (!Modifier.isTransient(field.getModifiers())) {
fields.put(field.getName(), createSchema(context, clazz, field.getType(), field.getGenericType()));
}
}
newSchema.setProperties(fields);
}
// If there is an extending class, add the data
if (clazz.getSuperclass() != null) {
Class<?> superClass = clazz.getSuperclass();
// If the super class is legitimate
if (!superClass.equals(Object.class) && !superClass.equals(Enum.class)) {
// Get the parent schema annotation
Schema parentSchema = superClass.getDeclaredAnnotation(Schema.class);
// Create a schema for the parent
visitSchema(parentSchema, superClass, context);
// Get the superclass schema name
String parentSchemaName = (parentSchema == null) ? null : parentSchema.name();
if (parentSchemaName == null || parentSchemaName.isEmpty()) {
parentSchemaName = superClass.getSimpleName();
}
// Link the schemas
newSchema.addAllOf(new SchemaImpl().ref(parentSchemaName));
}
}
}
private static void visitSchemaField(Schema schema, Field field, ApiContext context) {
// Get the schema object name
String schemaName = schema.name();
if (schemaName == null || schemaName.isEmpty()) {
schemaName = field.getName();
}
// Get the parent schema object name
String parentName = null;
if (field.getDeclaringClass().isAnnotationPresent(Schema.class)) {
parentName = field.getDeclaringClass().getDeclaredAnnotation(Schema.class).name();
}
if (parentName == null || parentName.isEmpty()) {
parentName = field.getDeclaringClass().getSimpleName();
}
// Get or create the parent schema object
org.eclipse.microprofile.openapi.models.media.Schema parent = context.getApi().getComponents().getSchemas()
.getOrDefault(parentName, new SchemaImpl());
context.getApi().getComponents().getSchemas().put(parentName, parent);
org.eclipse.microprofile.openapi.models.media.Schema property = new SchemaImpl();
parent.addProperty(schemaName, property);
property.setType(ModelUtils.getSchemaType(field.getType()));
SchemaImpl.merge(schema, property, true, context.getApi().getComponents().getSchemas());
}
private static void visitSchemaParameter(Schema schema, java.lang.reflect.Parameter parameter, ApiContext context) {
// If this is being parsed at the start, ignore it as the path doesn't exist
if (context.getWorkingOperation() == null) {
return;
}
// Check if it's a request body
if (ModelUtils.isRequestBody(parameter)) {
if (context.getWorkingOperation().getRequestBody() == null) {
context.getWorkingOperation().setRequestBody(new RequestBodyImpl());
}
// Insert the schema to the request body media type
MediaType mediaType = context.getWorkingOperation().getRequestBody().getContent()
.getMediaType(javax.ws.rs.core.MediaType.WILDCARD);
SchemaImpl.merge(schema, mediaType.getSchema(), true, context.getApi().getComponents().getSchemas());
if (schema.ref() != null && !schema.ref().isEmpty()) {
mediaType.setSchema(new SchemaImpl().ref(schema.ref()));
}
} else if (ModelUtils.getParameterType(parameter) != null) {
for (org.eclipse.microprofile.openapi.models.parameters.Parameter param : context.getWorkingOperation()
.getParameters()) {
if (param.getName().equals(ModelUtils.getParameterName(parameter))) {
SchemaImpl.merge(schema, param.getSchema(), true,
context.getApi().getComponents().getSchemas());
if (schema.ref() != null && !schema.ref().isEmpty()) {
param.setSchema(new SchemaImpl().ref(schema.ref()));
}
}
}
}
}
@Override
public void visitExtension(Extension extension, AnnotatedElement element, ApiContext context) {
String value = extension.value();
String name = extension.name();
if (name != null && !name.isEmpty() && value != null
&& !value.isEmpty()) {
Object parsedValue = ExtensibleImpl.convertExtensionValue(value, extension.parseValue());
if (element instanceof Method) {
context.getWorkingOperation().addExtension(name, parsedValue);
} else {
context.getApi().addExtension(name, parsedValue);
}
}
}
@Override
public void visitExtensions(Extensions extensions, AnnotatedElement element, ApiContext context) {
for (Extension extension : extensions.value()) {
visitExtension(extension, element, context);
}
}
@Override
public void visitOperation(Operation operation, AnnotatedElement element, ApiContext context) {
OperationImpl.merge(operation, context.getWorkingOperation(), true);
// If the operation should be hidden, remove it
if (operation.hidden()) {
ModelUtils.removeOperation(context.getApi().getPaths().getPathItem(context.getPath()),
context.getWorkingOperation());
}
}
@Override
public void visitCallback(Callback callback, AnnotatedElement element, ApiContext context) {
if (element instanceof Method) {
org.eclipse.microprofile.openapi.models.callbacks.Callback callbackModel = context.getWorkingOperation()
.getCallbacks().getOrDefault(callback.name(), new CallbackImpl());
context.getWorkingOperation().getCallbacks().put(callback.name(), callbackModel);
CallbackImpl.merge(callback, callbackModel, true, context.getApi().getComponents().getSchemas());
}
}
@Override
public void visitCallbacks(Callbacks callbacks, AnnotatedElement element, ApiContext context) {
for (Callback callback : callbacks.value()) {
visitCallback(callback, element, context);
}
}
@Override
public void visitRequestBody(RequestBody requestBody, AnnotatedElement element, ApiContext context) {
if (element instanceof Method || element instanceof java.lang.reflect.Parameter) {
org.eclipse.microprofile.openapi.models.parameters.RequestBody currentRequestBody = context
.getWorkingOperation().getRequestBody();
if (currentRequestBody != null || element instanceof java.lang.reflect.Parameter) {
RequestBodyImpl.merge(requestBody, currentRequestBody, true,
context.getApi().getComponents().getSchemas());
}
}
}
@Override
public void visitAPIResponse(APIResponse apiResponse, AnnotatedElement element, ApiContext context) {
APIResponsesImpl.merge(apiResponse, context.getWorkingOperation().getResponses(), true,
context.getApi().getComponents().getSchemas());
// If an APIResponse has been processed that isn't the default
if (apiResponse.responseCode() != null && !apiResponse.responseCode().isEmpty() && !apiResponse.responseCode()
.equals(org.eclipse.microprofile.openapi.models.responses.APIResponses.DEFAULT)) {
// If the element doesn't also contain a response mapping to the default
if (Arrays.asList(element.getDeclaredAnnotationsByType(APIResponse.class)).stream()
.noneMatch(a -> a.responseCode() == null || a.responseCode().isEmpty() || a.responseCode()
.equals(org.eclipse.microprofile.openapi.models.responses.APIResponses.DEFAULT))) {
// Then remove the default response
context.getWorkingOperation().getResponses()
.removeAPIResponse(org.eclipse.microprofile.openapi.models.responses.APIResponses.DEFAULT);
}
}
}
@Override
public void visitAPIResponses(APIResponses apiResponses, AnnotatedElement element, ApiContext context) {
for (APIResponse response : apiResponses.value()) {
visitAPIResponse(response, element, context);
}
}
@Override
public void visitParameters(Parameters parameters, AnnotatedElement element, ApiContext context) {
for (Parameter parameter : parameters.value()) {
visitParameter(parameter, element, context);
}
}
@Override
public void visitParameter(Parameter parameter, AnnotatedElement element, ApiContext context) {
org.eclipse.microprofile.openapi.models.parameters.Parameter matchedParam = null;
if (element instanceof java.lang.reflect.Parameter) {
matchedParam = findOperationParameterFor((java.lang.reflect.Parameter) element, context);
}
if (element instanceof Method) {
matchedParam = findOperationParameterFor(parameter, (Method) element, context);
}
if (matchedParam != null) {
ParameterImpl.merge(parameter, matchedParam, true, context.getApi().getComponents().getSchemas());
// If a content was added, and a schema type exists, reconfigure the schema type
if (matchedParam.getContent() != null && matchedParam.getSchema() != null
&& matchedParam.getSchema().getType() != null) {
SchemaType type = matchedParam.getSchema().getType();
matchedParam.setSchema(null);
for (MediaType mediaType : matchedParam.getContent().values()) {
if (mediaType.getSchema() == null) {
mediaType.setSchema(new SchemaImpl());
}
mediaType.getSchema()
.setType(ModelUtils.mergeProperty(mediaType.getSchema().getType(), type, false));
}
}
}
}
private static org.eclipse.microprofile.openapi.models.parameters.Parameter findOperationParameterFor(Parameter parameter,
Method annotated, ApiContext context) {
String name = parameter.name();
// If the parameter reference is valid
if (name != null && !name.isEmpty()) {
// Get all parameters with the same name
List<java.lang.reflect.Parameter> matchingMethodParameters = Arrays
.asList(annotated.getParameters()).stream()
.filter(x -> name.equals(ModelUtils.getParameterName(x)))
.collect(Collectors.toList());
// If there is more than one match, filter it further
ParameterIn in = parameter.in();
if (matchingMethodParameters.size() > 1 && in != null && in != ParameterIn.DEFAULT) {
// Remove all parameters of the wrong input type
matchingMethodParameters
.removeIf(x -> ModelUtils.getParameterType(x) != In.valueOf(in.name()));
}
if (matchingMethodParameters.isEmpty()) {
return null;
}
// If there's only one matching parameter, handle it immediately
String matchingMethodParamName = ModelUtils.getParameterName(matchingMethodParameters.get(0));
// Find the matching operation parameter
for (org.eclipse.microprofile.openapi.models.parameters.Parameter operationParam : context
.getWorkingOperation().getParameters()) {
if (operationParam.getName().equals(matchingMethodParamName)) {
return operationParam;
}
}
}
return null;
}
/**
* Find the matching parameter, and match it
*/
private static org.eclipse.microprofile.openapi.models.parameters.Parameter findOperationParameterFor(
java.lang.reflect.Parameter annotated, ApiContext context) {
String actualName = ModelUtils.getParameterName(annotated);
if (actualName == null) {
return null;
}
for (org.eclipse.microprofile.openapi.models.parameters.Parameter param : context.getWorkingOperation()
.getParameters()) {
if (actualName.equals(param.getName())) {
return param;
}
}
return null;
}
@Override
public void visitExternalDocumentation(ExternalDocumentation externalDocs, AnnotatedElement element,
ApiContext context) {
if (element instanceof Method) {
org.eclipse.microprofile.openapi.models.ExternalDocumentation newExternalDocs = new ExternalDocumentationImpl();
ExternalDocumentationImpl.merge(externalDocs, newExternalDocs, true);
if (newExternalDocs.getUrl() != null && !newExternalDocs.getUrl().isEmpty()) {
context.getWorkingOperation().setExternalDocs(newExternalDocs);
}
}
}
@Override
public void visitServer(Server server, AnnotatedElement element, ApiContext context) {
if (element instanceof Method) {
org.eclipse.microprofile.openapi.models.servers.Server newServer = new ServerImpl();
context.getWorkingOperation().addServer(newServer);
ServerImpl.merge(server, newServer, true);
}
}
@Override
public void visitServers(Servers servers, AnnotatedElement element, ApiContext context) {
for (Server server : servers.value()) {
visitServer(server, element, context);
}
}
@Override
public void visitTag(Tag tag, AnnotatedElement element, ApiContext context) {
if (element instanceof Method) {
TagImpl.merge(tag, context.getWorkingOperation(), true, context.getApi().getTags());
} else {
org.eclipse.microprofile.openapi.models.tags.Tag newTag = new TagImpl();
TagImpl.merge(tag, newTag, true);
if (newTag.getName() != null && !newTag.getName().isEmpty()) {
context.getApi().getTags().add(newTag);
}
}
}
@Override
public void visitTags(Tags tags, AnnotatedElement element, ApiContext context) {
if (element instanceof Method) {
for (Tag tag : tags.value()) {
visitTag(tag, element, context);
}
for (String ref : tags.refs()) {
if (ref != null && !ref.isEmpty()) {
context.getWorkingOperation().addTag(ref);
}
}
}
}
@Override
public void visitSecurityScheme(SecurityScheme securityScheme, AnnotatedElement element, ApiContext context) {
if (securityScheme.securitySchemeName() != null && !securityScheme.securitySchemeName().isEmpty()) {
org.eclipse.microprofile.openapi.models.security.SecurityScheme newScheme = context.getApi().getComponents()
.getSecuritySchemes().getOrDefault(securityScheme.securitySchemeName(), new SecuritySchemeImpl());
context.getApi().getComponents().addSecurityScheme(securityScheme.securitySchemeName(), newScheme);
SecuritySchemeImpl.merge(securityScheme, newScheme, true);
}
}
@Override
public void visitSecuritySchemes(SecuritySchemes securitySchemes, AnnotatedElement element, ApiContext context) {
for (SecurityScheme securityScheme : securitySchemes.value()) {
visitSecurityScheme(securityScheme, element, context);
}
}
@Override
public void visitSecurityRequirement(SecurityRequirement securityRequirement, AnnotatedElement element,
ApiContext context) {
if (element instanceof Method) {
if (securityRequirement.name() != null && !securityRequirement.name().isEmpty()) {
org.eclipse.microprofile.openapi.models.security.SecurityRequirement model = new SecurityRequirementImpl();
SecurityRequirementImpl.merge(securityRequirement, model);
context.getWorkingOperation().addSecurityRequirement(model);
}
}
}
@Override
public void visitSecurityRequirements(SecurityRequirements securityRequirements, AnnotatedElement element,
ApiContext context) {
for (SecurityRequirement requirement : securityRequirements.value()) {
visitSecurityRequirement(requirement, element, context);
}
}
// PRIVATE METHODS
private org.eclipse.microprofile.openapi.models.parameters.RequestBody insertDefaultRequestBody(ApiContext context,
org.eclipse.microprofile.openapi.models.Operation operation, Method method) {
org.eclipse.microprofile.openapi.models.parameters.RequestBody requestBody = new RequestBodyImpl();
// Get the request body type of the method
Class<?> bodyType = null;
Type genericBodyType = null;
for (java.lang.reflect.Parameter methodParam : method.getParameters()) {
if (ModelUtils.isRequestBody(methodParam)) {
bodyType = methodParam.getType();
genericBodyType = methodParam.getParameterizedType();
break;
}
}
if (bodyType == null) {
return null;
}
// Create the default request body with a wildcard mediatype
MediaType mediaType = new MediaTypeImpl().schema(createSchema(context, bodyType, genericBodyType));
requestBody.getContent().addMediaType(javax.ws.rs.core.MediaType.WILDCARD, mediaType);
operation.setRequestBody(requestBody);
return requestBody;
}
/**
* Creates a new {@link APIResponse} to model the default response of a
* {@link Method}, and inserts it into the {@link Operation} responses.
*
* @param context the API context.
* @param operation the {@link Operation} to add the default response to.
* @param method the {@link Method} to model the default response on.
* @return the newly created {@link APIResponse}.
*/
private org.eclipse.microprofile.openapi.models.responses.APIResponse insertDefaultResponse(ApiContext context,
org.eclipse.microprofile.openapi.models.Operation operation, Method method) {
org.eclipse.microprofile.openapi.models.responses.APIResponse defaultResponse = new APIResponseImpl();
defaultResponse.setDescription("Default Response.");
// Create the default response with a wildcard mediatype
MediaType mediaType = new MediaTypeImpl().schema(createSchema(context, method.getReturnType(), method.getGenericReturnType()));
defaultResponse.getContent().addMediaType(javax.ws.rs.core.MediaType.WILDCARD, mediaType);
// Add the default response
operation.setResponses(new APIResponsesImpl().addAPIResponse(
org.eclipse.microprofile.openapi.models.responses.APIResponses.DEFAULT, defaultResponse));
return defaultResponse;
}
/**
* @return the {@link javax.ws.rs.core.MediaType} with the given name. Defaults
* to <code>WILDCARD</code>.
*/
private static String getContentType(String name) {
String contentType = javax.ws.rs.core.MediaType.WILDCARD;
try {
javax.ws.rs.core.MediaType mediaType = javax.ws.rs.core.MediaType.valueOf(name);
if (mediaType != null) {
contentType = mediaType.toString();
}
} catch (IllegalArgumentException ex) {
LOGGER.log(FINE, "Unrecognised content type.", ex);
}
return contentType;
}
private org.eclipse.microprofile.openapi.models.media.Schema createSchema(ApiContext context, Class<?> type, Type genericType) {
org.eclipse.microprofile.openapi.models.media.Schema schema = new SchemaImpl();
SchemaType schemaType = ModelUtils.getSchemaType(type);
schema.setType(schemaType);
// Set the subtype if it's an array (for example an array of ints)
if (schemaType == SchemaType.ARRAY) {
if (type.isArray()) {
schema.setItems(createSchema(context, type.getComponentType(), type.getComponentType()));
} else { // should be something Iterable
ParameterizedType fullType = (ParameterizedType) genericType;
Type genericElementType = fullType.getActualTypeArguments()[0];
Class<?> rawElementType = (Class<?>) (genericElementType.getClass() == Class.class
? genericElementType
: ((ParameterizedType)genericElementType).getRawType());
schema.setItems(createSchema(context, rawElementType, genericElementType));
}
}
// If the schema is an object, insert the reference
if (schemaType == SchemaType.OBJECT) {
if (insertObjectReference(context, schema, type)) {
schema.setType(null);
schema.setItems(null);
}
}
return schema;
}
private org.eclipse.microprofile.openapi.models.media.Schema createSchema(ApiContext context,
AnnotatedElement annotatedElement, Class<?> type, Type genericType) {
SchemaType schemaType = ModelUtils.getSchemaType(type);
// If the annotated element is the same type as the reference class, return a null schema
if (schemaType == SchemaType.OBJECT && type.equals(annotatedElement)) {
org.eclipse.microprofile.openapi.models.media.Schema schema = new SchemaImpl();