|
| 1 | +package io.ipdata.client; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.JsonNode; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.fasterxml.jackson.databind.node.ArrayNode; |
| 6 | +import com.fasterxml.jackson.databind.node.ObjectNode; |
| 7 | +import com.google.common.io.CharStreams; |
| 8 | +import com.sun.net.httpserver.HttpExchange; |
| 9 | +import com.sun.net.httpserver.HttpServer; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.InputStream; |
| 13 | +import java.io.InputStreamReader; |
| 14 | +import java.io.UnsupportedEncodingException; |
| 15 | +import java.net.InetSocketAddress; |
| 16 | +import java.net.URLDecoder; |
| 17 | +import java.util.ArrayList; |
| 18 | +import java.util.HashMap; |
| 19 | +import java.util.List; |
| 20 | +import java.util.Map; |
| 21 | + |
| 22 | +public class MockIpdataServer { |
| 23 | + |
| 24 | + public static final String API_KEY = "test-api-key"; |
| 25 | + |
| 26 | + private static MockIpdataServer instance; |
| 27 | + |
| 28 | + private final HttpServer server; |
| 29 | + private final String url; |
| 30 | + private final Map<String, JsonNode> fixtures = new HashMap<>(); |
| 31 | + private final ObjectMapper mapper = new ObjectMapper(); |
| 32 | + |
| 33 | + private MockIpdataServer() { |
| 34 | + try { |
| 35 | + server = HttpServer.create(new InetSocketAddress(0), 0); |
| 36 | + int port = server.getAddress().getPort(); |
| 37 | + url = "http://localhost:" + port; |
| 38 | + loadFixtures(); |
| 39 | + server.createContext("/", this::handleRequest); |
| 40 | + server.start(); |
| 41 | + } catch (IOException e) { |
| 42 | + throw new RuntimeException("Failed to start mock server", e); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public static synchronized MockIpdataServer getInstance() { |
| 47 | + if (instance == null) { |
| 48 | + instance = new MockIpdataServer(); |
| 49 | + } |
| 50 | + return instance; |
| 51 | + } |
| 52 | + |
| 53 | + public String getUrl() { |
| 54 | + return url; |
| 55 | + } |
| 56 | + |
| 57 | + private void loadFixtures() { |
| 58 | + String[] ips = {"8.8.8.8", "2001:4860:4860::8888", "1.1.1.1", "2001:4860:4860::8844", "41.128.21.123"}; |
| 59 | + for (String ip : ips) { |
| 60 | + String resourceName = "fixtures/" + ip.replace(":", "-") + ".json"; |
| 61 | + try (InputStream is = getClass().getResourceAsStream(resourceName)) { |
| 62 | + if (is != null) { |
| 63 | + fixtures.put(ip, mapper.readTree(is)); |
| 64 | + } |
| 65 | + } catch (IOException e) { |
| 66 | + throw new RuntimeException("Failed to load fixture: " + resourceName, e); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + private void handleRequest(HttpExchange exchange) throws IOException { |
| 72 | + try { |
| 73 | + String method = exchange.getRequestMethod(); |
| 74 | + String path = exchange.getRequestURI().getPath(); |
| 75 | + String rawQuery = exchange.getRequestURI().getRawQuery(); |
| 76 | + Map<String, String> params = parseQuery(rawQuery); |
| 77 | + |
| 78 | + String apiKey = params.get("api-key"); |
| 79 | + if (!API_KEY.equals(apiKey)) { |
| 80 | + sendError(exchange, 401, "Invalid API key"); |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + if ("POST".equals(method) && "/bulk".equals(path)) { |
| 85 | + handleBulk(exchange); |
| 86 | + return; |
| 87 | + } |
| 88 | + |
| 89 | + if ("GET".equals(method)) { |
| 90 | + handleGet(exchange, path, params); |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + sendError(exchange, 404, "Not found"); |
| 95 | + } catch (Exception e) { |
| 96 | + sendError(exchange, 500, e.getMessage()); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + private void handleGet(HttpExchange exchange, String path, Map<String, String> params) throws IOException { |
| 101 | + String trimmed = path.startsWith("/") ? path.substring(1) : path; |
| 102 | + |
| 103 | + String ip = null; |
| 104 | + String field = null; |
| 105 | + |
| 106 | + // Match against known IPs (longest first to avoid prefix conflicts) |
| 107 | + List<String> sortedIps = new ArrayList<>(fixtures.keySet()); |
| 108 | + sortedIps.sort((a, b) -> b.length() - a.length()); |
| 109 | + |
| 110 | + for (String knownIp : sortedIps) { |
| 111 | + if (trimmed.equals(knownIp)) { |
| 112 | + ip = knownIp; |
| 113 | + break; |
| 114 | + } |
| 115 | + if (trimmed.startsWith(knownIp + "/")) { |
| 116 | + ip = knownIp; |
| 117 | + field = trimmed.substring(knownIp.length() + 1); |
| 118 | + break; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + if (ip == null) { |
| 123 | + sendError(exchange, 404, "IP not found"); |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + JsonNode fixture = fixtures.get(ip); |
| 128 | + |
| 129 | + if (field != null) { |
| 130 | + // Sub-field request: GET /{ip}/{field} |
| 131 | + JsonNode fieldNode = fixture.get(field); |
| 132 | + if (fieldNode == null) { |
| 133 | + sendError(exchange, 404, "Field not found: " + field); |
| 134 | + return; |
| 135 | + } |
| 136 | + if (fieldNode.isTextual()) { |
| 137 | + sendResponse(exchange, 200, fieldNode.asText()); |
| 138 | + } else { |
| 139 | + sendResponse(exchange, 200, mapper.writeValueAsString(fieldNode)); |
| 140 | + } |
| 141 | + } else if (params.containsKey("fields")) { |
| 142 | + // Selected fields request: GET /{ip}?fields=a,b |
| 143 | + String fieldsStr = params.get("fields"); |
| 144 | + String[] fields = fieldsStr.split(","); |
| 145 | + ObjectNode result = mapper.createObjectNode(); |
| 146 | + for (String f : fields) { |
| 147 | + JsonNode fieldNode = fixture.get(f.trim()); |
| 148 | + if (fieldNode != null) { |
| 149 | + result.set(f.trim(), fieldNode); |
| 150 | + } |
| 151 | + } |
| 152 | + sendResponse(exchange, 200, mapper.writeValueAsString(result)); |
| 153 | + } else { |
| 154 | + // Full model request: GET /{ip} |
| 155 | + sendResponse(exchange, 200, mapper.writeValueAsString(fixture)); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + private void handleBulk(HttpExchange exchange) throws IOException { |
| 160 | + String body = CharStreams.toString(new InputStreamReader(exchange.getRequestBody())); |
| 161 | + String[] ips = mapper.readValue(body, String[].class); |
| 162 | + ArrayNode result = mapper.createArrayNode(); |
| 163 | + for (String ip : ips) { |
| 164 | + JsonNode fixture = fixtures.get(ip); |
| 165 | + if (fixture != null) { |
| 166 | + result.add(fixture); |
| 167 | + } |
| 168 | + } |
| 169 | + sendResponse(exchange, 200, mapper.writeValueAsString(result)); |
| 170 | + } |
| 171 | + |
| 172 | + private void sendResponse(HttpExchange exchange, int status, String body) throws IOException { |
| 173 | + byte[] bytes = body.getBytes("UTF-8"); |
| 174 | + exchange.getResponseHeaders().set("Content-Type", "application/json"); |
| 175 | + exchange.sendResponseHeaders(status, bytes.length); |
| 176 | + exchange.getResponseBody().write(bytes); |
| 177 | + exchange.getResponseBody().close(); |
| 178 | + } |
| 179 | + |
| 180 | + private void sendError(HttpExchange exchange, int status, String message) throws IOException { |
| 181 | + String body = "{\"message\":\"" + message.replace("\"", "\\\"") + "\"}"; |
| 182 | + sendResponse(exchange, status, body); |
| 183 | + } |
| 184 | + |
| 185 | + private Map<String, String> parseQuery(String rawQuery) { |
| 186 | + Map<String, String> params = new HashMap<>(); |
| 187 | + if (rawQuery != null) { |
| 188 | + for (String param : rawQuery.split("&")) { |
| 189 | + String[] pair = param.split("=", 2); |
| 190 | + if (pair.length == 2) { |
| 191 | + try { |
| 192 | + params.put(URLDecoder.decode(pair[0], "UTF-8"), URLDecoder.decode(pair[1], "UTF-8")); |
| 193 | + } catch (UnsupportedEncodingException e) { |
| 194 | + params.put(pair[0], pair[1]); |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + return params; |
| 200 | + } |
| 201 | +} |
0 commit comments