-
Notifications
You must be signed in to change notification settings - Fork 549
Expand file tree
/
Copy pathOpenAPIV3Parser.java
More file actions
344 lines (308 loc) · 14.4 KB
/
OpenAPIV3Parser.java
File metadata and controls
344 lines (308 loc) · 14.4 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
package io.swagger.v3.parser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.extensions.SwaggerParserExtension;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import io.swagger.v3.parser.exception.EncodingNotSupportedException;
import io.swagger.v3.parser.exception.ReadContentException;
import io.swagger.v3.parser.reference.DereferencerContext;
import io.swagger.v3.parser.reference.DereferencersFactory;
import io.swagger.v3.parser.reference.OpenAPIDereferencer;
import io.swagger.v3.parser.util.ClasspathHelper;
import io.swagger.v3.parser.util.DeserializationUtils;
import io.swagger.v3.parser.util.InlineModelResolver;
import io.swagger.v3.parser.util.OpenAPIDeserializer;
import io.swagger.v3.parser.util.RemoteUrl;
import io.swagger.v3.parser.util.ResolverFully;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;
import javax.net.ssl.SSLHandshakeException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OpenAPIV3Parser implements SwaggerParserExtension {
public static final String DISABLE_OAS31_RESOLVE = "disableOas31Resolve";
private static final Logger LOGGER = LoggerFactory.getLogger(OpenAPIV3Parser.class);
private static ObjectMapper JSON_MAPPER, YAML_MAPPER;
/**
* Encoding of the resource content with OpenAPI spec to parse.
*/
private static String encoding = StandardCharsets.UTF_8.displayName();
static {
JSON_MAPPER = ObjectMapperFactory.createJson();
YAML_MAPPER = ObjectMapperFactory.createYaml();
}
/**
* Locates extensions on the current thread class loader and then, if it differs from this class classloader (as in
* OSGi), locates extensions from this class classloader as well.
* @return a list of extensions
*/
public static List<SwaggerParserExtension> getExtensions() {
final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
final List<SwaggerParserExtension> extensions = getExtensions(tccl);
final ClassLoader cl = SwaggerParserExtension.class.getClassLoader();
if (cl != tccl) {
extensions.addAll(getExtensions(cl));
}
extensions.add(0, new OpenAPIV3Parser());
return extensions;
}
protected static List<SwaggerParserExtension> getExtensions(ClassLoader cl) {
final List<SwaggerParserExtension> extensions = new ArrayList<>();
final ServiceLoader<SwaggerParserExtension> loader = ServiceLoader.load(SwaggerParserExtension.class, cl);
for (SwaggerParserExtension extension : loader) {
extensions.add(extension);
}
return extensions;
}
public static String getEncoding() {
return encoding;
}
public static void setEncoding(String encoding) {
if (!Charset.isSupported(encoding)) {
throw new EncodingNotSupportedException(encoding);
}
OpenAPIV3Parser.encoding = encoding;
}
@Override
public SwaggerParseResult readLocation(String url, List<AuthorizationValue> auth, ParseOptions options) {
try {
final String content = readContentFromLocation(url, emptyListIfNull(auth));
LOGGER.debug("Loaded raw data: {}", content);
return readContents(content, auth, options, url);
} catch (ReadContentException e) {
LOGGER.warn("Exception while reading:", e);
return SwaggerParseResult.ofError(e.getMessage());
}
}
@Override
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth,
ParseOptions options) {
return readContents(swaggerAsString, auth, options, null);
}
public OpenAPI read(String location) {
final ParseOptions options = new ParseOptions();
options.setResolve(true);
return read(location, null, options);
}
public OpenAPI read(String location, List<AuthorizationValue> auths, ParseOptions resolve) {
if (location == null) {
return null;
}
final List<SwaggerParserExtension> parserExtensions = getExtensions();
SwaggerParseResult parsed;
for (SwaggerParserExtension extension : parserExtensions) {
parsed = extension.readLocation(location, auths, resolve);
if (parsed.getMessages() != null) {
for (String message : parsed.getMessages()) {
LOGGER.info("{}: {}", extension, message);
}
}
final OpenAPI result = parsed.getOpenAPI();
if (result != null) {
return result;
}
}
return null;
}
@Deprecated
public SwaggerParseResult readWithInfo(String path, JsonNode node) {
return parseJsonNode(path, node);
}
public SwaggerParseResult parseJsonNode(String path, JsonNode node) {
return new OpenAPIDeserializer().deserialize(node, path,new ParseOptions());
}
public SwaggerParseResult parseJsonNode(String path, JsonNode node, ParseOptions options) {
return new OpenAPIDeserializer().deserialize(node, path, options, options.isOaiAuthor());
}
public SwaggerParseResult readContents(String yaml) {
final ParseOptions options = new ParseOptions();
options.setResolve(true);
return readContents(yaml, null, options);
}
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options,
String location) {
if (swaggerAsString == null || swaggerAsString.trim().isEmpty()) {
return SwaggerParseResult.ofError("Null or empty definition");
}
try {
final ObjectMapper mapper = getRightMapper(swaggerAsString);
JsonNode rootNode;
final SwaggerParseResult deserializationUtilsResult = new SwaggerParseResult();
if (options != null && options.isLegacyYamlDeserialization()) {
rootNode = mapper.readTree(swaggerAsString);
} else {
try {
rootNode = DeserializationUtils.deserializeIntoTree(swaggerAsString, location, options, deserializationUtilsResult);
} catch (Exception e) {
rootNode = mapper.readTree(swaggerAsString);
}
}
SwaggerParseResult result;
if (options != null) {
result = parseJsonNode(location, rootNode, options);
} else {
result = parseJsonNode(location, rootNode);
}
if (result.getOpenAPI() != null) {
result = resolve(result, auth, options, location);
}
if (deserializationUtilsResult.getMessages() != null) {
for (String s: deserializationUtilsResult.getMessages()) {
result.message(getParseErrorMessage(s, location));
}
}
return result;
} catch (JsonProcessingException e) {
LOGGER.warn("Exception while parsing:", e);
final String message = getParseErrorMessage(e.getOriginalMessage(), location);
return SwaggerParseResult.ofError(message);
} catch (Exception e) {
LOGGER.warn("Exception while parsing:", e);
final String message = getParseErrorMessage(e.getMessage(), location);
return SwaggerParseResult.ofError(message);
}
}
@Deprecated
public SwaggerParseResult readWithInfo(String location, List<AuthorizationValue> auths) {
return readContents(readContentFromLocation(location, auths), auths, null);
}
private SwaggerParseResult resolve(SwaggerParseResult result, List<AuthorizationValue> auth, ParseOptions options,
String location) {
try {
if (options != null) {
if (options.isResolve() || options.isResolveFully()) {
if (result.getOpenAPI().getOpenapi() != null && result.getOpenAPI().getOpenapi().startsWith("3.1")) {
if (StringUtils.isBlank(System.getenv(DISABLE_OAS31_RESOLVE))) {
DereferencerContext dereferencerContext = new DereferencerContext(
result,
auth,
location,
options,
null,
null,
true
);
List<OpenAPIDereferencer> dereferencers = DereferencersFactory.getInstance().getDereferencers();
if (dereferencers.iterator().hasNext()) {
OpenAPIDereferencer dereferencer = dereferencers.iterator().next();
dereferencer.dereference(dereferencerContext, dereferencers.iterator());
}
if (options.isResolveFully()) {
new ResolverFully(options.isResolveCombinators()).resolveFully(result.getOpenAPI());
}
} else {
String msg = "Resolution of OAS 3.1 spec disabled by 'disableOas31Resolve' env variable";
LOGGER.warn(msg);
result.getMessages().add(msg);
}
} else {
OpenAPIResolver resolver = new OpenAPIResolver(result.getOpenAPI(), emptyListIfNull(auth),
location, null, options);
resolver.resolve(result);
if (options.isResolveFully()) {
new ResolverFully(options.isResolveCombinators()).resolveFully(result.getOpenAPI());
}
}
}
if (options.isFlatten()) {
final InlineModelResolver inlineModelResolver =
new InlineModelResolver(options.isFlattenComposedSchemas(),
options.isCamelCaseFlattenNaming(), options.isSkipMatches());
if (result.getOpenAPI()!= null) {
inlineModelResolver.flatten(result.getOpenAPI());
}
}
}
} catch (Exception e) {
LOGGER.warn("Exception while resolving:", e);
// TODO verify if this change makes sense (adding resolve messages instead of replacing)
result.getMessages().add(e.getMessage());
// result.setMessages(Collections.singletonList(e.getMessage()));
}
return result;
}
private String getParseErrorMessage(String originalMessage, String location) {
if (Objects.isNull(originalMessage)) {
return String.format("Unable to parse `%s`", location);
}
if (originalMessage.startsWith("Duplicate field")) {
return String.format("%s in `%s`", originalMessage, location);
}
return originalMessage;
}
private <T> List<T> emptyListIfNull(List<T> list) {
return Objects.isNull(list) ? new ArrayList<>() : list;
}
private ObjectMapper getRightMapper(String data) {
if (data.trim().startsWith("{")) {
return JSON_MAPPER;
}
return YAML_MAPPER;
}
private String readContentFromLocation(String location, List<AuthorizationValue> auth) {
final String adjustedLocation = location.replaceAll("\\\\", "/");
try {
if (adjustedLocation.toLowerCase().startsWith("http")) {
return RemoteUrl.urlToString(adjustedLocation, auth);
} else if (adjustedLocation.toLowerCase().startsWith("jar:")) {
final InputStream in = new URI(adjustedLocation).toURL().openStream();
return IOUtils.toString(in, encoding);
} else {
final String fileScheme = "file:";
final Path path = adjustedLocation.toLowerCase().startsWith(fileScheme) ?
Paths.get(URI.create(adjustedLocation)) : Paths.get(adjustedLocation);
if (Files.exists(path)) {
return FileUtils.readFileToString(path.toFile(), encoding);
} else {
return ClasspathHelper.loadFileFromClasspath(adjustedLocation);
}
}
} catch (SSLHandshakeException e) {
final String message = String.format(
"Unable to read location `%s` due to a SSL configuration error. It is possible that the server SSL certificate is invalid, self-signed, or has an untrusted Certificate Authority.",
adjustedLocation);
throw new ReadContentException(message, e);
} catch (Exception e) {
throw new ReadContentException(String.format("Unable to read location `%s`", adjustedLocation), e);
}
}
/**
* Transform the swagger-model version of AuthorizationValue into a parser-specific one, to avoid
* dependencies across extensions
*
* @param input
* @return
*/
@Deprecated
protected List<AuthorizationValue> transform(List<AuthorizationValue> input) {
if(input == null) {
return null;
}
List<AuthorizationValue> output = new ArrayList<>();
for(AuthorizationValue value : input) {
AuthorizationValue v = new AuthorizationValue();
v.setKeyName(value.getKeyName());
v.setValue(value.getValue());
v.setType(value.getType());
v.setUrlMatcher(value.getUrlMatcher());
output.add(v);
}
return output;
}
}