|
| 1 | +package apiaddicts.sonar.openapi.utils; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.OutputStream; |
| 5 | +import java.net.InetSocketAddress; |
| 6 | +import java.nio.file.Files; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.nio.file.Paths; |
| 9 | + |
| 10 | +import com.sun.net.httpserver.HttpExchange; |
| 11 | +import com.sun.net.httpserver.HttpServer; |
| 12 | + |
| 13 | +public final class ExternalRefHttpServer { |
| 14 | + |
| 15 | + public static final int PORT = 18089; |
| 16 | + public static final String BASE_URL = "http://localhost:" + PORT; |
| 17 | + |
| 18 | + private static final Path FIXTURES = Paths.get("src", "test", "resources", "externalRef").toAbsolutePath().normalize(); |
| 19 | + |
| 20 | + private static HttpServer server; |
| 21 | + |
| 22 | + private ExternalRefHttpServer() { |
| 23 | + } |
| 24 | + |
| 25 | + public static synchronized void start() { |
| 26 | + if (server != null) { |
| 27 | + return; |
| 28 | + } |
| 29 | + try { |
| 30 | + HttpServer s = HttpServer.create(new InetSocketAddress("127.0.0.1", PORT), 0); |
| 31 | + s.createContext("/", ExternalRefHttpServer::handle); |
| 32 | + s.setExecutor(null); |
| 33 | + s.start(); |
| 34 | + Runtime.getRuntime().addShutdownHook(new Thread(() -> s.stop(0))); |
| 35 | + server = s; |
| 36 | + } catch (IOException e) { |
| 37 | + throw new IllegalStateException("Could not start external ref HTTP server on port " + PORT, e); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private static void handle(HttpExchange exchange) throws IOException { |
| 42 | + try { |
| 43 | + String name = exchange.getRequestURI().getPath().replaceFirst("^/+", ""); |
| 44 | + Path file = FIXTURES.resolve(name).normalize(); |
| 45 | + if (!file.startsWith(FIXTURES) || !Files.isRegularFile(file)) { |
| 46 | + exchange.sendResponseHeaders(404, -1); |
| 47 | + return; |
| 48 | + } |
| 49 | + byte[] body = Files.readAllBytes(file); |
| 50 | + exchange.getResponseHeaders().set("Content-Type", "application/yaml; charset=utf-8"); |
| 51 | + exchange.sendResponseHeaders(200, body.length); |
| 52 | + try (OutputStream os = exchange.getResponseBody()) { |
| 53 | + os.write(body); |
| 54 | + } |
| 55 | + } finally { |
| 56 | + exchange.close(); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments