-
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathOpenAPIModule.java
More file actions
289 lines (256 loc) · 8.41 KB
/
OpenAPIModule.java
File metadata and controls
289 lines (256 loc) · 8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.jspecify.annotations.Nullable;
import io.jooby.SneakyThrows.Consumer2;
import io.jooby.handler.Asset;
import io.jooby.handler.AssetSource;
import io.jooby.internal.IOUtils;
import io.jooby.internal.OpenAPIAsset;
/**
* OpenAPI supports for Jooby. Basic Usage:
*
* <pre>{@code
* {
* install(new OpenAPIModule());
* }
* }</pre>
*
* The <code>[openapi].json</code> and/or <code>[openapi].yaml</code> files must be present on
* classpath.
*
* <p>If <code>jooby-swagger-ui</code> is present (part of your project classpath) swagger-ui will
* be available. Same for <code>jooby-redoc</code>.
*
* <p>Complete documentation is available at: https://jooby.io/modules/openapi
*
* @author edgar
* @since 2.7.0
*/
public class OpenAPIModule implements Extension {
private static class OpenAPISource implements AssetSource {
private final Map<String, Asset> assets = new HashMap<>();
public OpenAPISource put(String key, Asset asset) {
assets.put(key, asset);
return this;
}
@Nullable @Override
public Asset resolve(String path) {
return assets.get(path);
}
}
/** Available formats. */
public enum Format {
/** JSON. */
JSON,
/** YAML. */
YAML;
/**
* Find format based on files extension.
*
* @param filePath File name.
* @return File format.
*/
public static Format from(String filePath) {
for (Format value : values()) {
if (filePath.endsWith("." + value.name().toLowerCase())) {
return value;
}
}
throw new IllegalArgumentException("Unsupported format: " + filePath);
}
}
private final String openAPIPath;
private String swaggerUIPath = "/swagger";
private String redocPath = "/redoc";
private EnumSet<Format> format = EnumSet.of(Format.JSON, Format.YAML);
private final Set<String> customFiles = new LinkedHashSet<>();
private String contextPath;
/**
* Creates an OpenAPI module. The path is used to route the open API files. For example:
*
* <pre>{@code
* install(new OpenAPIModule("/docs"));
* }</pre>
*
* Files will be at <code>/docs/openapi.json</code>, <code>/docs/openapi.yaml</code>.
*
* @param path Custom path to use.
*/
public OpenAPIModule(String path) {
this.openAPIPath = Router.normalizePath(path);
}
/**
* Creates an OpenAPI module.
*
* <p>Files will be at <code>/openapi.json</code>, <code>/openapi.yaml</code>.
*/
public OpenAPIModule() {
this("/");
}
/**
* Set custom openapi file to use. Could be a file system or classpath resource.
*
* @param path Path.
* @return This module.
*/
public OpenAPIModule file(String path) {
customFiles.add(path);
return this;
}
/**
* Set/override context path of OpenAPI resource. Helps when it runs behind a proxy on a different
* context path or path prefix.
*
* @param contextPath Context path/Path prefix.
* @return This module.
*/
public OpenAPIModule contextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
/**
* Customize the swagger-ui path. Defaults is <code>/swagger</code>.
*
* @param path Swagger-ui path.
* @return This module.
*/
public OpenAPIModule swaggerUI(String path) {
this.swaggerUIPath = Router.normalizePath(path);
return this;
}
/**
* Customize the redoc-ui path. Defaults is <code>/redoc</code>.
*
* @param path Redoc path.
* @return This module.
*/
public OpenAPIModule redoc(String path) {
this.redocPath = Router.normalizePath(path);
return this;
}
/**
* Enable what format are available (json or yaml).
*
* <p>IMPORTANT: UI tools requires the JSON format.
*
* @param format Supported formats.
* @return This module.
*/
public OpenAPIModule format(Format... format) {
this.format = EnumSet.copyOf(Arrays.asList(format));
return this;
}
@Override
public void install(Jooby application) throws Exception {
var filePaths = computeOpenAPIFiles(application);
/*
Add /openapi.json and/or /openapi.yaml paths
*/
filePaths.forEach((path, source) -> application.assets(fullPath(openAPIPath, path), source));
/** Configure UI: */
configureUI(application);
}
private Map<String, String> computeOpenAPIFiles(Jooby application) {
final Map<String, String> filePaths = new LinkedHashMap<>();
if (customFiles.isEmpty()) {
// Generated by open api
String dir = Optional.ofNullable(application.getBasePackage()).orElse("/").replace(".", "/");
String appName =
application
.getClass()
.getSimpleName()
.replace("Jooby", "openapi")
.replace("Kooby", "openapi");
for (Format ext : format) {
String filename = String.format("/%s.%s", appName, ext.name().toLowerCase());
String openAPIFileLocation = Router.normalizePath(dir) + filename;
filePaths.put("/openapi." + ext.name().toLowerCase(), openAPIFileLocation);
}
} else {
// Custom files
for (String file : customFiles) {
filePaths.put("/openapi." + Format.from(file).name().toLowerCase(), file);
}
}
return filePaths;
}
private void configureUI(Jooby application) {
Map<String, Consumer2<Jooby, AssetSource>> ui = new HashMap<>();
ui.put("swagger-ui", this::swaggerUI);
ui.put("redoc", this::redoc);
ClassLoader classLoader = application.getClassLoader();
for (Map.Entry<String, Consumer2<Jooby, AssetSource>> e : ui.entrySet()) {
String name = e.getKey();
if (classLoader.getResource(name + "/index.html") != null) {
if (format.contains(Format.JSON)) {
Consumer2<Jooby, AssetSource> consumer = e.getValue();
consumer.accept(application, AssetSource.create(classLoader, name));
} else {
application.getLog().debug("{} is disabled when json format is not supported", name);
}
}
}
}
private void redoc(Jooby application, AssetSource source) throws Exception {
String openAPIJSON = fullPath(fullPath(contextPath(application), openAPIPath), "/openapi.json");
AssetSource customSource =
new OpenAPISource()
.put(
"index.html",
processAsset(
source,
MediaType.html,
"index.html",
"${openAPIPath}",
openAPIJSON,
"${redocPath}",
fullPath(contextPath(application), redocPath)));
application.assets(redocPath + "/?*", customSource, source);
}
private void swaggerUI(Jooby application, AssetSource source) throws Exception {
String openAPIJSON = fullPath(fullPath(contextPath(application), openAPIPath), "/openapi.json");
AssetSource customSource =
new OpenAPISource()
.put(
"index.html",
processAsset(
source,
MediaType.html,
"index.html",
"${swaggerPath}",
fullPath(contextPath(application), swaggerUIPath)))
.put(
"swagger-initializer.js",
processAsset(
source,
MediaType.html,
"swagger-initializer.js",
"${openAPIPath}",
openAPIJSON));
application.assets(swaggerUIPath + "/?*", customSource, source);
}
private static Asset processAsset(
AssetSource source, MediaType type, String resource, String... replacements)
throws Exception {
try (Asset asset = source.resolve(resource)) {
String content = IOUtils.toString(asset.stream(), StandardCharsets.UTF_8);
for (int i = 0; i < replacements.length; i += 2) {
content = content.replace(replacements[i], replacements[i + 1]);
}
return new OpenAPIAsset(
type, content.getBytes(StandardCharsets.UTF_8), asset.getLastModified());
}
}
private static String fullPath(String contextPath, String path) {
return Router.noTrailingSlash(Router.normalizePath(contextPath + path));
}
private String contextPath(Jooby application) {
return contextPath == null ? application.getContextPath() : contextPath;
}
}