|
| 1 | +package io.github.simbo1905.json.schema; |
| 2 | + |
| 3 | +import com.sun.net.httpserver.HttpExchange; |
| 4 | +import com.sun.net.httpserver.HttpHandler; |
| 5 | +import com.sun.net.httpserver.HttpServer; |
| 6 | +import org.junit.jupiter.api.extension.AfterAllCallback; |
| 7 | +import org.junit.jupiter.api.extension.BeforeAllCallback; |
| 8 | +import org.junit.jupiter.api.extension.ExtensionContext; |
| 9 | + |
| 10 | +import java.io.IOException; |
| 11 | +import java.io.OutputStream; |
| 12 | +import java.net.InetSocketAddress; |
| 13 | +import java.nio.charset.StandardCharsets; |
| 14 | +import java.util.Map; |
| 15 | + |
| 16 | +final class RemoteSchemaServerRule implements BeforeAllCallback, AfterAllCallback { |
| 17 | + private HttpServer server; |
| 18 | + private String host; |
| 19 | + private int port; |
| 20 | + |
| 21 | + @Override |
| 22 | + public void beforeAll(ExtensionContext context) throws Exception { |
| 23 | + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); |
| 24 | + host = "127.0.0.1"; |
| 25 | + port = server.getAddress().getPort(); |
| 26 | + |
| 27 | + // Basic example document |
| 28 | + addJson("/a.json", "{\n \"$id\": \"http://" + host + ":" + port + "/a.json\",\n \"$defs\": {\n \"X\": {\"type\": \"integer\", \"minimum\": 1},\n \"Y\": {\"type\": \"string\", \"minLength\": 1}\n }\n}\n"); |
| 29 | + |
| 30 | + // Simple second doc |
| 31 | + addJson("/b.json", "{\n \"$id\": \"http://" + host + ":" + port + "/b.json\",\n \"type\": \"string\"\n}\n"); |
| 32 | + |
| 33 | + // 2-node cycle |
| 34 | + addJson("/cycle1.json", "{\n \"$id\": \"http://" + host + ":" + port + "/cycle1.json\",\n \"$ref\": \"http://" + host + ":" + port + "/cycle2.json#\"\n}\n"); |
| 35 | + addJson("/cycle2.json", "{\n \"$id\": \"http://" + host + ":" + port + "/cycle2.json\",\n \"$ref\": \"http://" + host + ":" + port + "/cycle1.json#\"\n}\n"); |
| 36 | + |
| 37 | + server.start(); |
| 38 | + } |
| 39 | + |
| 40 | + private void addJson(String path, String body) { |
| 41 | + server.createContext(path, new JsonResponder(body)); |
| 42 | + } |
| 43 | + |
| 44 | + String url(String path) { return "http://" + host + ":" + port + path; } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void afterAll(ExtensionContext context) { |
| 48 | + if (server != null) server.stop(0); |
| 49 | + } |
| 50 | + |
| 51 | + private static final class JsonResponder implements HttpHandler { |
| 52 | + private final byte[] bytes; |
| 53 | + JsonResponder(String body) { this.bytes = body.getBytes(StandardCharsets.UTF_8); } |
| 54 | + @Override public void handle(HttpExchange exchange) throws IOException { |
| 55 | + exchange.getResponseHeaders().add("Content-Type", "application/schema+json"); |
| 56 | + exchange.sendResponseHeaders(200, bytes.length); |
| 57 | + try (OutputStream os = exchange.getResponseBody()) { os.write(bytes); } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments