forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAPIModule.java
More file actions
257 lines (217 loc) · 7.24 KB
/
OpenAPIModule.java
File metadata and controls
257 lines (217 loc) · 7.24 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
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import io.jooby.SneakyThrows.Consumer2;
/**
* 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.
*
* If <code>jooby-swagger-ui</code> is present (part of your project classpath) swagger-ui will
* be available. Same for <code>jooby-redoc</code>.
*
* Complete documentation is available at: https://jooby.io/modules/openapi
*
* @author edgar
* @since 2.7.0
*/
public class OpenAPIModule implements Extension {
private static class OpenAPIAsset implements Asset {
private long lastModified;
private byte[] content;
private MediaType type;
OpenAPIAsset(MediaType type, byte[] content, long lastModified) {
this.content = content;
this.type = type;
this.lastModified = lastModified;
}
@Override public long getSize() {
return content.length;
}
@Override public long getLastModified() {
return lastModified;
}
@Override public boolean isDirectory() {
return false;
}
@NotNull @Override public MediaType getContentType() {
return type;
}
@Override public InputStream stream() {
return new ByteArrayInputStream(content);
}
@Override public void close() throws Exception {
// NOOP
}
}
private static class OpenAPISource implements AssetSource {
private Map<String, Asset> assets = new HashMap<>();
public OpenAPISource put(String key, Asset asset) {
assets.put(key, asset);
return this;
}
@Nullable @Override public Asset resolve(@NotNull String path) {
return assets.get(path);
}
}
/**
* Available formats.
*/
public enum Format {
/**
* JSON.
*/
JSON,
/**
* YAML.
*/
YAML
}
private final String openAPIPath;
private String swaggerUIPath = "/swagger";
private String redocPath = "/redoc";
private EnumSet<Format> format = EnumSet.of(Format.JSON, Format.YAML);
/**
* 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(@Nonnull String path) {
this.openAPIPath = Router.normalizePath(path);
}
/**
* Creates an OpenAPI module.
*
* Files will be at <code>/openapi.json</code>, <code>/openapi.yaml</code>.
*/
public OpenAPIModule() {
this("/");
}
/**
* Customize the swagger-ui path. Defaults is <code>/swagger</code>.
*
* @param path Swagger-ui path.
* @return This module.
*/
public @Nonnull OpenAPIModule swaggerUI(@Nonnull 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 @Nonnull OpenAPIModule redoc(@Nonnull String path) {
this.redocPath = Router.normalizePath(path);
return this;
}
/**
* Enable what format are available (json or yaml).
*
* IMPORTANT: UI tools requires the JSON format.
*
* @param format Supported formats.
* @return This module.
*/
public @Nonnull OpenAPIModule format(@Nonnull Format... format) {
this.format = EnumSet.copyOf(Arrays.asList(format));
return this;
}
@Override public void install(@Nonnull Jooby application) throws Exception {
String dir = Optional.ofNullable(application.getBasePackage())
.orElse("/")
.replace(".", "/");
String appname = application.getName()
.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;
application.assets(fullPath(openAPIPath, "/openapi." + ext.name().toLowerCase()),
openAPIFileLocation);
}
/** Configure UI: */
configureUI(application);
}
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(application.getContextPath(), openAPIPath), "/openapi.json");
AssetSource customSource = new OpenAPISource()
.put("index.html",
processAsset(source, MediaType.html, "index.html", "${openAPIPath}", openAPIJSON,
"${redocPath}", fullPath(application.getContextPath(), redocPath)));
application.assets(redocPath + "/?*", customSource, source);
}
private void swaggerUI(Jooby application, AssetSource source) throws Exception {
String openAPIJSON = fullPath(
fullPath(application.getContextPath(), openAPIPath), "/openapi.json");
AssetSource customSource = new OpenAPISource()
.put("index.html", processAsset(source, MediaType.html, "index.html", "${swaggerPath}",
fullPath(application.getContextPath(), 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));
}
}