-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpec.java
More file actions
413 lines (384 loc) · 16.1 KB
/
Copy pathSpec.java
File metadata and controls
413 lines (384 loc) · 16.1 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
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
package com.retailsvc.http.spec;
import com.retailsvc.http.spec.schema.Schema;
import com.retailsvc.http.spec.schema.SchemaParser;
import com.retailsvc.http.spec.security.SecurityRequirement;
import com.retailsvc.http.spec.security.SecurityScheme;
import com.retailsvc.http.spec.security.SecuritySchemeParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
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.function.Function;
public record Spec(
String openapi,
Info info,
List<Server> servers,
List<Operation> operations,
Map<String, Schema> componentSchemas,
Map<String, Parameter> componentParameters,
String basePath,
Map<String, Schema> schemaRefIndex,
Map<String, Parameter> parameterRefIndex,
Map<String, Object> extensions,
Map<String, SecurityScheme> securitySchemes,
List<SecurityRequirement> security) {
private static final String SCHEMA_KEY = "schema";
private static final String SECURITY_KEY = "security";
private static final String SCHEMA_REF_PREFIX = "#/components/schemas/";
private static final String PARAMETER_REF_PREFIX = "#/components/parameters/";
static Map<String, Object> extractExtensions(Map<String, Object> raw) {
Map<String, Object> out = new LinkedHashMap<>();
for (var e : raw.entrySet()) {
if (e.getKey().startsWith("x-")) {
out.put(e.getKey(), e.getValue());
}
}
return Map.copyOf(out);
}
private static final String GSON_CLASS = "com.google.gson.Gson";
private static final String SNAKEYAML_CLASS = "org.yaml.snakeyaml.Yaml";
/**
* Loads an OpenAPI specification from a classpath resource. Picks the parser by file extension:
*
* <ul>
* <li>{@code .json} → Gson must be on the classpath.
* <li>{@code .yaml} or {@code .yml} → SnakeYAML must be on the classpath.
* </ul>
*
* <p>{@code resource} is resolved via {@link Class#getResourceAsStream(String)}: a leading {@code
* /} is absolute (JAR root), otherwise it is package-relative to {@code loader}. Use {@code
* "/openapi.yaml"} for a spec packaged at the root of {@code src/main/resources/}.
*
* @throws NullPointerException if {@code loader} or {@code resource} is {@code null}
* @throws IllegalArgumentException if the resource is not found on the classpath
* @throws IllegalStateException if the file has an unrecognised extension, or the required parser
* is not on the classpath
*/
public static Spec fromClasspath(Class<?> loader, String resource) {
Objects.requireNonNull(loader, "loader");
Objects.requireNonNull(resource, "resource");
String name = resource.toLowerCase(Locale.ROOT);
boolean isJson = name.endsWith(".json");
boolean isYaml = name.endsWith(".yaml") || name.endsWith(".yml");
if (!isJson && !isYaml) {
throw new IllegalStateException(
"Unrecognised OpenAPI spec extension for "
+ resource
+ " — expected .json, .yaml, or .yml.");
}
InputStream in = loader.getResourceAsStream(resource);
if (in == null) {
throw new IllegalArgumentException("classpath resource not found: " + resource);
}
return isJson ? fromJson(in) : fromYaml(in);
}
/**
* Reads a JSON OpenAPI specification from {@code in} using Gson. Gson must be on the classpath;
* otherwise throws {@link IllegalStateException}. The stream is fully consumed and closed before
* this method returns.
*
* <p>Useful for loading specs from the classpath:
*
* <pre>{@code
* try (InputStream in = getClass().getResourceAsStream("/openapi.json")) {
* Spec spec = Spec.fromJson(in);
* }
* }</pre>
*
* <p>To avoid the Gson dependency (e.g. when using Jackson), use {@link #fromJson(InputStream,
* Function)} instead.
*
* @throws NullPointerException if {@code in} is {@code null}
* @throws UncheckedIOException if the stream cannot be read
* @throws IllegalStateException if Gson is not on the classpath
*/
public static Spec fromJson(InputStream in) {
return fromJson(in, Spec::parseJsonWithGson);
}
/**
* Reads a JSON OpenAPI specification from {@code in} using the supplied {@code parser}. The
* parser receives the full body as bytes and returns the decoded map. The stream is fully
* consumed and closed before this method returns.
*
* <p>Example with Jackson:
*
* <pre>{@code
* ObjectMapper mapper = new ObjectMapper();
* Spec spec = Spec.fromJson(in, bytes -> mapper.readValue(bytes, Map.class));
* }</pre>
*
* @throws NullPointerException if {@code in} or {@code parser} is {@code null}
* @throws UncheckedIOException if the stream cannot be read
*/
public static Spec fromJson(InputStream in, Function<byte[], Map<String, Object>> parser) {
Objects.requireNonNull(parser, "parser");
return from(parser.apply(readAll(in)));
}
/**
* Reads a YAML OpenAPI specification from {@code in} using SnakeYAML. SnakeYAML must be on the
* classpath; otherwise throws {@link IllegalStateException}. The stream is fully consumed and
* closed before this method returns.
*
* @throws NullPointerException if {@code in} is {@code null}
* @throws UncheckedIOException if the stream cannot be read
* @throws IllegalStateException if SnakeYAML is not on the classpath
*/
public static Spec fromYaml(InputStream in) {
return from(parseYamlWithSnakeYaml(readAll(in)));
}
private static byte[] readAll(InputStream in) {
Objects.requireNonNull(in, "in");
try (in) {
return in.readAllBytes();
} catch (IOException e) {
throw new UncheckedIOException("Failed to read OpenAPI spec from stream", e);
}
}
private static Map<String, Object> parseJsonWithGson(byte[] bytes) {
String text = new String(bytes, StandardCharsets.UTF_8);
Class<?> gsonClass = loadOptional(GSON_CLASS, "Json", "Gson");
try {
Object gson = gsonClass.getDeclaredConstructor().newInstance();
Method fromJson = gsonClass.getMethod("fromJson", String.class, Class.class);
@SuppressWarnings("unchecked")
Map<String, Object> raw = (Map<String, Object>) fromJson.invoke(gson, text, Map.class);
return raw;
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Failed to parse OpenAPI spec via Gson", e);
}
}
private static Map<String, Object> parseYamlWithSnakeYaml(byte[] bytes) {
String text = new String(bytes, StandardCharsets.UTF_8);
Class<?> yamlClass = loadOptional(SNAKEYAML_CLASS, "Yaml", "SnakeYAML");
try {
Object yaml = yamlClass.getDeclaredConstructor().newInstance();
Method load = yamlClass.getMethod("load", String.class);
@SuppressWarnings("unchecked")
Map<String, Object> raw = (Map<String, Object>) load.invoke(yaml, text);
return raw;
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Failed to parse OpenAPI spec via SnakeYAML", e);
}
}
private static Class<?> loadOptional(String className, String format, String libName) {
try {
return Class.forName(className, false, Spec.class.getClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Loading "
+ format
+ " OpenAPI specs requires "
+ libName
+ " on the classpath. Add a "
+ libName
+ " dependency, or supply your own parser via Spec.from"
+ format
+ "(InputStream, Function) / Spec.from(Map<String, Object>) instead.",
e);
}
}
@SuppressWarnings("unchecked")
public static Spec from(Map<String, Object> raw) {
String openapi = (String) raw.get("openapi");
Info info = parseInfo((Map<String, Object>) raw.get("info"));
List<Server> servers = parseServers((List<Map<String, Object>>) raw.get("servers"));
Map<String, Object> rawComponents =
(Map<String, Object>) raw.getOrDefault("components", Map.of());
Map<String, Schema> componentSchemas = parseComponentSchemas(rawComponents);
Map<String, Parameter> componentParameters = parseComponentParameters(rawComponents);
List<Operation> operations =
parseOperations(
(Map<String, Object>) raw.getOrDefault("paths", Map.of()), componentParameters);
Map<String, Object> rawSchemes =
(Map<String, Object>) rawComponents.getOrDefault("securitySchemes", Map.of());
Map<String, SecurityScheme> securitySchemes = new LinkedHashMap<>();
for (var entry : rawSchemes.entrySet()) {
securitySchemes.put(
entry.getKey(), SecuritySchemeParser.parse((Map<String, Object>) entry.getValue()));
}
List<SecurityRequirement> rootSecurity =
SecuritySchemeParser.parseRequirements((List<Object>) raw.get(SECURITY_KEY));
return new Spec(
openapi,
info,
servers,
operations,
componentSchemas,
componentParameters,
computeBasePath(servers),
indexByRef(componentSchemas, SCHEMA_REF_PREFIX),
indexByRef(componentParameters, PARAMETER_REF_PREFIX),
extractExtensions(raw),
Map.copyOf(securitySchemes),
rootSecurity);
}
private static String computeBasePath(List<Server> servers) {
if (servers.isEmpty()) {
throw new IllegalStateException("no servers declared");
}
String path = URI.create(servers.getFirst().url()).getPath();
return (path == null || path.isEmpty()) ? "/" : path;
}
private static <T> Map<String, T> indexByRef(Map<String, T> components, String prefix) {
Map<String, T> out = LinkedHashMap.newLinkedHashMap(components.size());
for (var e : components.entrySet()) {
out.put(prefix + e.getKey(), e.getValue());
}
return Map.copyOf(out);
}
public Schema resolveSchema(String ref) {
Schema s = schemaRefIndex.get(ref);
if (s == null) {
throw new IllegalArgumentException("unknown schema ref: " + ref);
}
return s;
}
public Parameter resolveParameter(String ref) {
Parameter p = parameterRefIndex.get(ref);
if (p == null) {
throw new IllegalArgumentException("unknown parameter ref: " + ref);
}
return p;
}
private static String stripPrefix(String ref, String prefix) {
if (!ref.startsWith(prefix)) {
throw new IllegalArgumentException("ref does not start with " + prefix + ": " + ref);
}
return ref.substring(prefix.length());
}
private static Info parseInfo(Map<String, Object> raw) {
return new Info((String) raw.get("title"), (String) raw.get("version"), extractExtensions(raw));
}
private static List<Server> parseServers(List<Map<String, Object>> raw) {
if (raw == null || raw.isEmpty()) {
return List.of();
}
return raw.stream().map(m -> new Server((String) m.get("url"))).toList();
}
@SuppressWarnings("unchecked")
private static Map<String, Schema> parseComponentSchemas(Map<String, Object> rawComponents) {
Map<String, Object> rawSchemas =
(Map<String, Object>) rawComponents.getOrDefault("schemas", Map.of());
Map<String, Schema> out = new LinkedHashMap<>();
for (var e : rawSchemas.entrySet()) {
out.put(e.getKey(), SchemaParser.parse(e.getValue()));
}
return Map.copyOf(out);
}
@SuppressWarnings("unchecked")
private static Map<String, Parameter> parseComponentParameters(
Map<String, Object> rawComponents) {
Map<String, Object> rawParams =
(Map<String, Object>) rawComponents.getOrDefault("parameters", Map.of());
Map<String, Parameter> out = new LinkedHashMap<>();
for (var e : rawParams.entrySet()) {
out.put(e.getKey(), parseParameter((Map<String, Object>) e.getValue()));
}
return Map.copyOf(out);
}
@SuppressWarnings("unchecked")
private static Parameter parseParameter(Map<String, Object> raw) {
return new Parameter(
(String) raw.get("name"),
Parameter.Location.valueOf(((String) raw.get("in")).toUpperCase(Locale.ROOT)),
Boolean.TRUE.equals(raw.get("required")),
SchemaParser.parse(raw.getOrDefault(SCHEMA_KEY, Map.of("type", "string"))));
}
@SuppressWarnings("unchecked")
private static List<Operation> parseOperations(
Map<String, Object> rawPaths, Map<String, Parameter> componentParameters) {
List<Operation> out = new ArrayList<>();
for (var pathEntry : rawPaths.entrySet()) {
PathTemplate template = PathTemplate.compile(pathEntry.getKey());
Map<String, Object> pathItem = (Map<String, Object>) pathEntry.getValue();
for (HttpMethod m : HttpMethod.values()) {
Object opRaw = pathItem.get(m.name().toLowerCase(Locale.ROOT));
if (opRaw instanceof Map<?, ?> opMap) {
out.add(parseOperation(m, template, (Map<String, Object>) opMap, componentParameters));
}
}
}
return List.copyOf(out);
}
@SuppressWarnings("unchecked")
private static Operation parseOperation(
HttpMethod method,
PathTemplate path,
Map<String, Object> raw,
Map<String, Parameter> componentParameters) {
String opId = (String) raw.get("operationId");
Optional<RequestBody> body =
Optional.ofNullable((Map<String, Object>) raw.get("requestBody"))
.map(Spec::parseRequestBody);
List<Parameter> params =
Optional.ofNullable((List<Map<String, Object>>) raw.get("parameters"))
.map(
list ->
list.stream()
.map(p -> resolveParameterOrParse(p, componentParameters))
.toList())
.orElse(List.of());
Map<String, Response> responses =
parseResponses((Map<String, Object>) raw.getOrDefault("responses", Map.of()));
Optional<List<SecurityRequirement>> opSecurity =
raw.containsKey(SECURITY_KEY)
? Optional.of(
SecuritySchemeParser.parseRequirements((List<Object>) raw.get(SECURITY_KEY)))
: Optional.empty();
return new Operation(
opId, method, path, body, params, responses, extractExtensions(raw), opSecurity);
}
private static Parameter resolveParameterOrParse(
Map<String, Object> raw, Map<String, Parameter> componentParameters) {
String ref = (String) raw.get("$ref");
if (ref != null) {
String name = stripPrefix(ref, PARAMETER_REF_PREFIX);
Parameter p = componentParameters.get(name);
if (p == null) {
throw new IllegalArgumentException("unknown parameter ref: " + ref);
}
return p;
}
return parseParameter(raw);
}
@SuppressWarnings("unchecked")
private static RequestBody parseRequestBody(Map<String, Object> raw) {
Map<String, Object> contentRaw = (Map<String, Object>) raw.getOrDefault("content", Map.of());
Map<String, MediaType> content = new LinkedHashMap<>();
for (var e : contentRaw.entrySet()) {
Map<String, Object> mt = (Map<String, Object>) e.getValue();
content.put(
e.getKey().toLowerCase(java.util.Locale.ROOT),
new MediaType(SchemaParser.parse(mt.getOrDefault(SCHEMA_KEY, Map.of("type", "object")))));
}
return new RequestBody(Boolean.TRUE.equals(raw.get("required")), Map.copyOf(content));
}
@SuppressWarnings("unchecked")
private static Map<String, Response> parseResponses(Map<String, Object> raw) {
Map<String, Response> out = new LinkedHashMap<>();
for (var e : raw.entrySet()) {
Map<String, Object> r = (Map<String, Object>) e.getValue();
Map<String, Object> contentRaw = (Map<String, Object>) r.getOrDefault("content", Map.of());
Map<String, MediaType> content = new LinkedHashMap<>();
for (var ce : contentRaw.entrySet()) {
Map<String, Object> mt = (Map<String, Object>) ce.getValue();
if (mt.containsKey(SCHEMA_KEY)) {
content.put(
ce.getKey().toLowerCase(java.util.Locale.ROOT),
new MediaType(SchemaParser.parse(mt.get(SCHEMA_KEY))));
}
}
out.put(e.getKey(), new Response(Map.copyOf(content)));
}
return Map.copyOf(out);
}
}