-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpecificationLoader.java
More file actions
57 lines (46 loc) · 1.92 KB
/
Copy pathSpecificationLoader.java
File metadata and controls
57 lines (46 loc) · 1.92 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
package com.retailsvc.http.openapi;
import com.retailsvc.http.openapi.exceptions.LoadSpecificationException;
import com.retailsvc.http.openapi.model.OpenApi;
import java.io.InputStream;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
public class SpecificationLoader {
private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public static byte[] load(String spec) {
LOG.debug("Loading specification from '{}'...", spec);
try (InputStream is = loadFile(spec)) {
return is.readAllBytes();
} catch (Exception e) {
String message = "Specification %s could not be loaded".formatted(spec);
throw new LoadSpecificationException(message, e);
}
}
/**
* @param specificationPath The path to OpenAPI specification
* @param mapper The mapper to serialize spec into an instance of {@link OpenApi}
* @return The openapi model
*/
public static OpenApi parseSpecification(
String specificationPath, Function<String, OpenApi> mapper, Function<Object, String> toJson) {
long t0 = System.currentTimeMillis();
byte[] data = load(specificationPath);
String openapiAsText = new String(data, StandardCharsets.UTF_8);
if (specificationPath.endsWith(".yaml") || specificationPath.endsWith(".yml")) {
var yaml = new Yaml();
Object yamlObj = yaml.load(openapiAsText);
openapiAsText = toJson.apply(yamlObj);
}
OpenApi spec = OpenApi.parse(mapper, openapiAsText);
LOG.debug(
"Parsed OpenAPI {} specification in {}ms", spec.openapi(), System.currentTimeMillis() - t0);
return spec;
}
private static InputStream loadFile(String spec) {
return SpecificationLoader.class.getClassLoader().getResourceAsStream(spec);
}
private SpecificationLoader() {}
}