-
Notifications
You must be signed in to change notification settings - Fork 86
/
SmallRyeOpenAPI.java
479 lines (415 loc) · 19.9 KB
/
SmallRyeOpenAPI.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
package io.smallrye.openapi.api;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.models.Components;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.Paths;
import org.eclipse.microprofile.openapi.models.media.Schema;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.Type;
import io.smallrye.openapi.api.models.OpenAPIImpl;
import io.smallrye.openapi.api.util.MergeUtil;
import io.smallrye.openapi.runtime.OpenApiProcessor;
import io.smallrye.openapi.runtime.OpenApiRuntimeException;
import io.smallrye.openapi.runtime.io.Format;
import io.smallrye.openapi.runtime.io.IOContext;
import io.smallrye.openapi.runtime.io.JsonIO;
import io.smallrye.openapi.runtime.io.OpenAPIDefinitionIO;
import io.smallrye.openapi.runtime.scanner.AnnotationScannerExtension;
import io.smallrye.openapi.runtime.scanner.FilteredIndexView;
import io.smallrye.openapi.runtime.scanner.OpenApiAnnotationScanner;
import io.smallrye.openapi.runtime.scanner.spi.AnnotationScanner;
import io.smallrye.openapi.runtime.scanner.spi.AnnotationScannerContext;
import io.smallrye.openapi.runtime.scanner.spi.AnnotationScannerFactory;
@SuppressWarnings("deprecation")
public class SmallRyeOpenAPI {
private final OpenAPI model;
private final Object jsonModel;
private final BiFunction<? super Object, Format, String> toString;
@SuppressWarnings("unchecked")
private SmallRyeOpenAPI(OpenAPI model, Object jsonModel, BiFunction<?, Format, String> toString) {
this.model = model;
this.jsonModel = jsonModel;
this.toString = (BiFunction<? super Object, Format, String>) toString;
}
public OpenAPI model() {
return model;
}
public String toJSON() {
return toString.apply(jsonModel, Format.JSON);
}
public String toYAML() {
return toString.apply(jsonModel, Format.YAML);
}
public static SmallRyeOpenAPI.Builder builder() {
return new SmallRyeOpenAPI.Builder();
}
public static class Builder {
private Config config;
private ClassLoader applicationClassLoader;
private OpenAPI initialModel;
private boolean enableModelReader = true;
private boolean enableStandardStaticFiles = true;
private Function<String, URL> resourceLocator;
private InputStream customStaticFile;
private boolean defaultRequiredProperties = true;
private IndexView index;
private boolean enableAnnotationScan = true;
private ClassLoader scannerClassLoader;
private Predicate<URL> staticFileFilter = f -> true;
private Predicate<String> scannerFilter = n -> true;
private Function<Collection<ClassInfo>, String> contextRootResolver = apps -> null;
private UnaryOperator<Type> typeConverter = UnaryOperator.identity();
private Function<String, Object> jsonParser = null;
private Function<String, Schema> schemaParser = null;
private boolean enableStandardFilter = true;
private Map<String, OASFilter> filters = new LinkedHashMap<>();
private Builder() {
}
/**
* Set the MicroProfile Config to be used when building the OpenAPI
* model. When not set, the builder will obtain a Config instance using
* {@link ConfigProvider#getConfig()} with the
* {@linkplain #withApplicationClassLoader(ClassLoader) application
* class loader}.
*
* @param config
* Config instance, nulls not allowed
* @return this builder
*/
public Builder withConfig(Config config) {
this.config = Objects.requireNonNull(config);
return this;
}
/**
* Set the application ClassLoader to be used when building the OpenAPI
* model.
*
* @param classLoader
* ClassLoader instance, nulls not allowed
* @return this builder
*/
public Builder withApplicationClassLoader(ClassLoader classLoader) {
this.applicationClassLoader = Objects.requireNonNull(classLoader);
return this;
}
/**
* Set an initial model used when building the OpenAPI model. The
* elements in this model will be overridden by any conflicting elements
* in models generated by the builder.
*
* @param initialModel
* initial OpenAPI model
* @return this builder
*/
public Builder withInitialModel(OpenAPI initialModel) {
this.initialModel = initialModel;
return this;
}
/**
* Enable (true) or disable (false) the lookup and use of an
* OASModelReader. Default is true.
*
* @param enableModelReader
* true if the model reader should be loaded and called,
* otherwise false.
* @return this builder
*/
public Builder enableModelReader(boolean enableModelReader) {
this.enableModelReader = enableModelReader;
return this;
}
/**
* Enable (true) or disable (false) the lookup and use of the standard
* static OpenAPI files (e.g. {@code META-INF/openapi.(json|yaml|yml)}.
* Default is true.
*
* @param enableStandardStaticFiles
* true if the standard static files should be loaded and
* included, otherwise false.
* @return this builder
*/
public Builder enableStandardStaticFiles(boolean enableStandardStaticFiles) {
this.enableStandardStaticFiles = enableStandardStaticFiles;
return this;
}
/**
* Enable (true) or disable (false) the lookup and use of the standard
* OASFilter. Default is true.
*
* @param enableStandardFilter
* true if the filter should be loaded and called, otherwise
* false.
* @return this builder
*/
public Builder enableStandardFilter(boolean enableStandardFilter) {
this.enableStandardFilter = enableStandardFilter;
return this;
}
/**
* Enable (true) or disable (false) setting default values for the
* OpenAPI properties listed below. Default is true.
*
* <ul>
* <li>Create an empty {@code paths} object if none specified
* <li>Set a generated value for {@code info.title} if none specified
* <li>Set a generated value for {@code info.version} if none specified
* <li>Set a default value for {@code openapi} (the specification
* version) if none specified. E.g. 3.0.3
* </ul>
*
* @param defaultRequiredProperties
* true if default values should be set when necessary,
* otherwise false.
* @return this builder
*/
public Builder defaultRequiredProperties(boolean defaultRequiredProperties) {
this.defaultRequiredProperties = defaultRequiredProperties;
return this;
}
/**
* Provide a resource locator function that when given a String path for
* a static file will return a URL that may be used to load the
* resource. This function is intended to support environments where the
* resource is not on the class path and an alternate loading approach
* is necessary, for example using a ServletContext.
*
* @param resourceLocator
* @return this builder
*/
public Builder withResourceLocator(Function<String, URL> resourceLocator) {
this.resourceLocator = resourceLocator;
return this;
}
/**
* Provide a custom static file that is not one of those in the standard locations
* or with a standard name. The user of this builder is responsible for closing the stream
* after {@linkplain #build()} has been invoked.
*
* @param customStaticFile
* @return
*/
public Builder withCustomStaticFile(InputStream customStaticFile) {
this.customStaticFile = customStaticFile;
return this;
}
public Builder setStaticFileFilter(Predicate<URL> staticFileFilter) {
this.staticFileFilter = Objects.requireNonNull(staticFileFilter);
return this;
}
public Builder withIndex(IndexView index) {
this.index = Objects.requireNonNull(index);
return this;
}
public Builder withContextRootResolver(Function<Collection<ClassInfo>, String> contextRootResolver) {
this.contextRootResolver = Objects.requireNonNull(contextRootResolver);
return this;
}
public Builder withTypeConverter(UnaryOperator<Type> typeConverter) {
this.typeConverter = Objects.requireNonNull(typeConverter);
return this;
}
public Builder withJsonParser(Function<String, Object> jsonParser) {
this.jsonParser = jsonParser;
return this;
}
public Builder withSchemaParser(Function<String, Schema> schemaParser) {
this.schemaParser = schemaParser;
return this;
}
public Builder enableAnnotationScan(boolean enableAnnotationScan) {
this.enableAnnotationScan = enableAnnotationScan;
return this;
}
public Builder withScannerClassLoader(ClassLoader scannerClassLoader) {
this.scannerClassLoader = scannerClassLoader;
return this;
}
public Builder withScannerFilter(Predicate<String> scannerFilter) {
this.scannerFilter = Objects.requireNonNull(scannerFilter);
return this;
}
public Builder withFilters(Collection<OASFilter> filters) {
Objects.requireNonNull(filters);
this.filters.clear();
filters.forEach(filter -> this.filters.put(filter.getClass().getName(), filter));
return this;
}
public Builder withFilterNames(Collection<String> filterNames) {
Objects.requireNonNull(filterNames);
filters.clear();
filterNames.forEach(filter -> this.filters.put(filter, null));
return this;
}
public Builder addFilter(OASFilter filter) {
Objects.requireNonNull(filter);
filters.put(filter.getClass().getName(), filter);
return this;
}
public Builder addFilterName(String filterName) {
Objects.requireNonNull(filterName);
filters.put(filterName, null);
return this;
}
public <V, A extends V, O extends V, AB, OB> SmallRyeOpenAPI build() {
ClassLoader appClassLoader = applicationClassLoader != null ? applicationClassLoader
: Thread.currentThread().getContextClassLoader();
OpenApiConfig buildConfig = OpenApiConfig.fromConfig(Optional.ofNullable(this.config)
.orElseGet(() -> ConfigProvider.getConfig(appClassLoader)));
IOContext<V, A, O, AB, OB> io = IOContext.forJson(JsonIO.newInstance(buildConfig));
OpenAPIDefinitionIO<V, A, O, AB, OB> modelIO = new OpenAPIDefinitionIO<>(io);
FilteredIndexView filteredIndex = new FilteredIndexView(index, buildConfig);
OpenAPI readerModel = null;
OpenAPI staticModel = null;
OpenAPI annotationModel = null;
OASFilter standardFilter = null;
if (enableModelReader) {
readerModel = OpenApiProcessor.modelFromReader(buildConfig, appClassLoader, filteredIndex);
debugModel("reader", readerModel);
}
if (enableStandardStaticFiles) {
Function<String, URL> loadFn = Optional.ofNullable(resourceLocator)
.orElse(appClassLoader::getResource);
staticModel = OpenApiProcessor.loadOpenApiStaticFiles(loadFn)
.stream()
.filter(file -> staticFileFilter.test(file.getLocator()))
.map(file -> {
try (Reader reader = new InputStreamReader(file.getContent())) {
V dom = io.jsonIO().fromReader(reader, file.getFormat());
OpenAPI fileModel = modelIO.readValue(dom);
debugModel("static file", fileModel);
return fileModel;
} catch (IOException e) {
throw new OpenApiRuntimeException("IOException reading " + file.getFormat() + " static file",
e);
}
})
.reduce(MergeUtil::merge)
.orElse(null);
}
if (customStaticFile != null) {
try (Reader reader = new InputStreamReader(customStaticFile)) {
V dom = io.jsonIO().fromReader(reader);
OpenAPI customStaticModel = modelIO.readValue(dom);
debugModel("static file", customStaticModel);
staticModel = MergeUtil.merge(customStaticModel, staticModel);
} catch (IOException e) {
throw new OpenApiRuntimeException("IOException reading custom static file", e);
}
}
if (enableAnnotationScan && !buildConfig.scanDisable()) {
AnnotationScannerExtension ext = newExtension(modelIO);
AnnotationScannerContext scannerContext = new AnnotationScannerContext(filteredIndex, appClassLoader,
Collections.singletonList(ext), false, buildConfig, modelIO, new OpenAPIImpl());
io.scannerContext(scannerContext);
Supplier<Iterable<AnnotationScanner>> supplier = Optional.ofNullable(scannerClassLoader)
.map(AnnotationScannerFactory::new)
.orElseGet(() -> new AnnotationScannerFactory(appClassLoader));
OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(scannerContext, supplier);
annotationModel = scanner.scan(scannerFilter);
debugModel("annotation", annotationModel);
}
if (enableStandardFilter) {
standardFilter = OpenApiProcessor.getFilter(buildConfig, appClassLoader, filteredIndex);
}
OpenApiDocument doc = OpenApiDocument.newInstance();
doc.config(buildConfig);
doc.defaultRequiredProperties(defaultRequiredProperties);
doc.modelFromReader(MergeUtil.merge(initialModel, readerModel));
doc.modelFromStaticFile(staticModel);
doc.modelFromAnnotations(annotationModel);
filters.entrySet()
.stream()
.map(e -> Optional.ofNullable(e.getValue())
// Create an instance from the key (class name) when the value is null
.orElseGet(() -> OpenApiProcessor.getFilter(e.getKey(), appClassLoader, filteredIndex)))
.forEach(doc::filter);
if (standardFilter != null && !filters.containsKey(standardFilter.getClass().getName())) {
doc.filter(standardFilter);
}
doc.initialize();
OpenAPI model = doc.get();
BiFunction<V, Format, String> toString = io.jsonIO()::toString;
return new SmallRyeOpenAPI(model, modelIO.write(model).orElse(null), toString);
}
private <V, A extends V, O extends V, AB, OB> AnnotationScannerExtension newExtension(
OpenAPIDefinitionIO<V, A, O, AB, OB> modelIO) {
return new AnnotationScannerExtension() {
@Override
public void processScannerApplications(AnnotationScanner scanner, Collection<ClassInfo> applications) {
Optional.ofNullable(contextRootResolver.apply(applications))
.ifPresent(scanner::setContextRoot);
}
@Override
public Type resolveAsyncType(Type type) {
return typeConverter.apply(type);
}
@Override
public Object parseValue(String value) {
return Optional.ofNullable(jsonParser)
.map(parser -> parser.apply(value))
.orElseGet(() -> modelIO.jsonIO().parseValue(value));
}
@Override
public Schema parseSchema(String jsonSchema) {
return Optional.ofNullable(schemaParser)
.map(parser -> parser.apply(jsonSchema))
.orElseGet(() -> {
V schemaModel = modelIO.jsonIO().fromString(jsonSchema, Format.JSON);
return modelIO.schemas().readValue(schemaModel);
});
}
};
}
private void debugModel(String source, OpenAPI model) {
if (model == null) {
return;
}
ApiLogging.logger.addingModel(source);
debugMap("callbacks", source, getMap(model, Components::getCallbacks));
debugMap("examples", source, getMap(model, Components::getExamples));
debugMap("headers", source, getMap(model, Components::getHeaders));
debugMap("links", source, getMap(model, Components::getLinks));
debugMap("parameters", source, getMap(model, Components::getParameters));
debugMap("request bodies", source, getMap(model, Components::getRequestBodies));
debugMap("responses", source, getMap(model, Components::getResponses));
debugMap("schemas", source, getMap(model, Components::getSchemas));
debugMap("security schemes", source, getMap(model, Components::getSecuritySchemes));
debugList("servers", source, Optional.ofNullable(model.getServers()));
debugMap("path items", source, Optional.ofNullable(model.getPaths()).map(Paths::getPathItems));
debugList("security", source, Optional.ofNullable(model.getSecurity()));
debugList("tags", source, Optional.ofNullable(model.getTags()));
debugMap("extensions", source, Optional.ofNullable(model.getExtensions()));
}
private Optional<Map<String, ?>> getMap(OpenAPI model, Function<Components, Map<String, ?>> extract) {
return Optional.ofNullable(model.getComponents()).map(extract);
}
private void debugMap(String name, String source, Optional<Map<String, ?>> collection) {
debugModel(name, source, collection.map(Map::size));
}
private void debugList(String name, String source, Optional<Collection<?>> collection) {
debugModel(name, source, collection.map(Collection::size));
}
private void debugModel(String name, String source, Optional<Integer> collection) {
ApiLogging.logger.addingModel(name, source, collection.map(Object::toString).orElse("<no>"));
}
}
}