|
| 1 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 2 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 3 | +import com.flagsmith.FlagsmithClient; |
| 4 | +import com.flagsmith.Versions; |
| 5 | +import com.flagsmith.models.BaseFlag; |
| 6 | +import com.flagsmith.models.Flags; |
| 7 | +import com.sun.net.httpserver.HttpExchange; |
| 8 | +import com.sun.net.httpserver.HttpServer; |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.OutputStream; |
| 11 | +import java.net.InetSocketAddress; |
| 12 | +import java.util.ArrayList; |
| 13 | +import java.util.HashMap; |
| 14 | +import java.util.LinkedHashMap; |
| 15 | +import java.util.List; |
| 16 | +import java.util.Map; |
| 17 | +import java.util.concurrent.ConcurrentHashMap; |
| 18 | +import java.util.concurrent.Executors; |
| 19 | +import java.util.concurrent.atomic.AtomicLong; |
| 20 | +import java.util.regex.Matcher; |
| 21 | +import java.util.regex.Pattern; |
| 22 | + |
| 23 | +/** |
| 24 | + * Adapter that lets the Flagsmith SDK behavioural spec drive this SDK. |
| 25 | + * |
| 26 | + * <p>Protocol: https://github.com/Flagsmith/sdk-spec/blob/main/ADAPTER.md |
| 27 | + */ |
| 28 | +public class Adapter { |
| 29 | + |
| 30 | + private static final ObjectMapper MAPPER = new ObjectMapper(); |
| 31 | + private static final TypeReference<Map<String, Object>> JSON_OBJECT = |
| 32 | + new TypeReference<Map<String, Object>>() {}; |
| 33 | + private static final Pattern CLIENT_ROUTE = |
| 34 | + Pattern.compile("^/clients/(?<clientId>[^/]+)(?<action>/[a-z-]+)?$"); |
| 35 | + |
| 36 | + private static final Map<String, FlagsmithClient> clients = new ConcurrentHashMap<>(); |
| 37 | + private static final AtomicLong clientIds = new AtomicLong(); |
| 38 | + |
| 39 | + public static void main(String[] args) throws IOException { |
| 40 | + int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080")); |
| 41 | + HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0); |
| 42 | + server.createContext("/", Adapter::dispatch); |
| 43 | + server.setExecutor(Executors.newCachedThreadPool()); |
| 44 | + server.start(); |
| 45 | + System.out.println("adapter: listening on :" + port); |
| 46 | + } |
| 47 | + |
| 48 | + private static void dispatch(HttpExchange exchange) throws IOException { |
| 49 | + try { |
| 50 | + route(exchange); |
| 51 | + } catch (Exception e) { |
| 52 | + // Report SDK errors to the runner. |
| 53 | + e.printStackTrace(); |
| 54 | + send(exchange, 500, error(e.getClass().getSimpleName() + ": " + e.getMessage())); |
| 55 | + } finally { |
| 56 | + System.out.println("adapter: " + exchange.getRequestMethod() + " " |
| 57 | + + exchange.getRequestURI() + " " + exchange.getResponseCode()); |
| 58 | + exchange.close(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + private static void route(HttpExchange exchange) throws Exception { |
| 63 | + String method = exchange.getRequestMethod(); |
| 64 | + String path = exchange.getRequestURI().getPath(); |
| 65 | + |
| 66 | + if (method.equals("GET") && path.equals("/health")) { |
| 67 | + Map<String, Object> health = new LinkedHashMap<>(); |
| 68 | + health.put("sdk", "flagsmith-java-client"); |
| 69 | + health.put("version", Versions.getVersion()); |
| 70 | + send(exchange, 200, health); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + if (method.equals("POST") && path.equals("/clients")) { |
| 75 | + Map<String, Object> body = body(exchange); |
| 76 | + String clientId = String.valueOf(clientIds.incrementAndGet()); |
| 77 | + clients.put(clientId, FlagsmithClient.newBuilder() |
| 78 | + .setApiKey((String) body.get("environmentKey")) |
| 79 | + .withApiUrl((String) body.get("apiUrl")) |
| 80 | + .build()); |
| 81 | + send(exchange, 201, Map.of("clientId", clientId)); |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + Matcher match = CLIENT_ROUTE.matcher(path); |
| 86 | + FlagsmithClient client = match.matches() ? clients.get(match.group("clientId")) : null; |
| 87 | + if (client == null) { |
| 88 | + send(exchange, 404, error("No route for " + method + " " + path)); |
| 89 | + return; |
| 90 | + } |
| 91 | + String action = match.group("action"); |
| 92 | + |
| 93 | + if (method.equals("DELETE") && action == null) { |
| 94 | + clients.remove(match.group("clientId")).close(); |
| 95 | + send(exchange, 204, null); |
| 96 | + return; |
| 97 | + } |
| 98 | + |
| 99 | + if (method.equals("POST") && "/environment-flags".equals(action)) { |
| 100 | + send(exchange, 200, serialiseFlags(client.getEnvironmentFlags())); |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + if (method.equals("POST") && "/identity-flags".equals(action)) { |
| 105 | + Map<String, Object> body = body(exchange); |
| 106 | + @SuppressWarnings("unchecked") |
| 107 | + Map<String, Object> traits = (Map<String, Object>) body.get("traits"); |
| 108 | + Flags flags = client.getIdentityFlags( |
| 109 | + (String) body.get("identifier"), traits != null ? traits : new HashMap<>()); |
| 110 | + send(exchange, 200, serialiseFlags(flags)); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + send(exchange, 404, error("No route for " + method + " " + path)); |
| 115 | + } |
| 116 | + |
| 117 | + private static Map<String, Object> serialiseFlags(Flags flags) { |
| 118 | + List<Map<String, Object>> serialised = new ArrayList<>(); |
| 119 | + for (BaseFlag flag : flags.getAllFlags()) { |
| 120 | + Map<String, Object> entry = new LinkedHashMap<>(); |
| 121 | + entry.put("featureName", flag.getFeatureName()); |
| 122 | + entry.put("enabled", flag.getEnabled()); |
| 123 | + // The SDK keeps API values as Jackson nodes, which serialise with their JSON type intact. |
| 124 | + entry.put("value", flag.getValue()); |
| 125 | + serialised.add(entry); |
| 126 | + } |
| 127 | + return Map.of("flags", serialised); |
| 128 | + } |
| 129 | + |
| 130 | + private static Map<String, Object> error(String message) { |
| 131 | + return Map.of("error", String.valueOf(message)); |
| 132 | + } |
| 133 | + |
| 134 | + private static Map<String, Object> body(HttpExchange exchange) throws IOException { |
| 135 | + byte[] bytes = exchange.getRequestBody().readAllBytes(); |
| 136 | + return bytes.length > 0 ? MAPPER.readValue(bytes, JSON_OBJECT) : new HashMap<>(); |
| 137 | + } |
| 138 | + |
| 139 | + private static void send(HttpExchange exchange, int status, Object body) throws IOException { |
| 140 | + if (body == null) { |
| 141 | + exchange.sendResponseHeaders(status, -1); |
| 142 | + return; |
| 143 | + } |
| 144 | + byte[] payload = MAPPER.writeValueAsBytes(body); |
| 145 | + exchange.getResponseHeaders().set("Content-Type", "application/json"); |
| 146 | + exchange.sendResponseHeaders(status, payload.length); |
| 147 | + try (OutputStream out = exchange.getResponseBody()) { |
| 148 | + out.write(payload); |
| 149 | + } |
| 150 | + } |
| 151 | +} |
0 commit comments