|
| 1 | +package com.contentstack.sdk; |
| 2 | + |
| 3 | +import org.json.JSONArray; |
| 4 | +import org.json.JSONException; |
| 5 | +import org.json.JSONObject; |
| 6 | + |
| 7 | +import java.io.InputStream; |
| 8 | +import java.net.HttpURLConnection; |
| 9 | +import java.net.URL; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.util.Iterator; |
| 12 | +import java.util.LinkedHashMap; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.Scanner; |
| 15 | +import java.util.logging.Logger; |
| 16 | + |
| 17 | +/** |
| 18 | + * Resolves Contentstack API endpoints for any region and service without hardcoding host strings. |
| 19 | + * |
| 20 | + * <h3>Resolution chain</h3> |
| 21 | + * <ol> |
| 22 | + * <li><b>In-memory cache</b> — populated on the first call and reused for the process lifetime |
| 23 | + * (zero I/O on every subsequent call).</li> |
| 24 | + * <li><b>Bundled {@code regions.json}</b> — read from the classpath resource |
| 25 | + * {@code /assets/regions.json} that is packaged inside the SDK. Works |
| 26 | + * fully offline with zero latency.</li> |
| 27 | + * <li><b>Live download</b> — if the requested region is not present in the bundled file |
| 28 | + * (e.g. Contentstack added a new region after this SDK version was released), a single |
| 29 | + * HTTP request is made to {@value #REGIONS_URL} to fetch the latest registry. The |
| 30 | + * downloaded data replaces the in-memory cache so all subsequent lookups benefit from it. |
| 31 | + * This attempt is made at most <em>once</em> per session to avoid repeated network |
| 32 | + * calls for genuinely invalid region strings.</li> |
| 33 | + * </ol> |
| 34 | + * |
| 35 | + * <p>Region matching is case-insensitive and treats {@code -} and {@code _} as equivalent |
| 36 | + * separators, so {@code "AZURE_NA"}, {@code "azure-na"}, and {@code "Azure_NA"} all resolve |
| 37 | + * to the same region. |
| 38 | + * |
| 39 | + * <p><b>Examples:</b> |
| 40 | + * <pre> |
| 41 | + * String url = Endpoint.getContentstackEndpoint("eu", "contentDelivery"); |
| 42 | + * // → "https://eu-cdn.contentstack.com" |
| 43 | + * |
| 44 | + * String host = Endpoint.getContentstackEndpoint("eu", "contentDelivery", true); |
| 45 | + * // → "eu-cdn.contentstack.com" |
| 46 | + * |
| 47 | + * Map<String, String> all = Endpoint.getAllEndpoints("azure-na"); |
| 48 | + * // → {"contentDelivery": "https://azure-na-cdn.contentstack.com", ...} |
| 49 | + * </pre> |
| 50 | + */ |
| 51 | +public class Endpoint { |
| 52 | + |
| 53 | + static final String REGIONS_URL = "https://artifacts.contentstack.com/regions.json"; |
| 54 | + |
| 55 | + private static final Logger logger = Logger.getLogger(Endpoint.class.getSimpleName()); |
| 56 | + |
| 57 | + private static volatile JSONArray regionsCache = null; |
| 58 | + |
| 59 | + private static volatile boolean liveRefreshDone = false; |
| 60 | + |
| 61 | + private Endpoint() { |
| 62 | + } |
| 63 | + |
| 64 | + public static String getContentstackEndpoint(String region, String service) { |
| 65 | + return getContentstackEndpoint(region, service, false); |
| 66 | + } |
| 67 | + |
| 68 | + public static String getContentstackEndpoint(String region, String service, boolean omitHttps) { |
| 69 | + if (region == null || region.trim().isEmpty()) { |
| 70 | + throw new IllegalArgumentException("Empty region provided. Please provide a valid region."); |
| 71 | + } |
| 72 | + JSONObject regionRow = resolveRegion(region); |
| 73 | + try { |
| 74 | + JSONObject endpoints = regionRow.getJSONObject("endpoints"); |
| 75 | + if (!endpoints.has(service)) { |
| 76 | + throw new IllegalArgumentException( |
| 77 | + "Service \"" + service + "\" not found for region \"" + region + "\""); |
| 78 | + } |
| 79 | + String url = endpoints.getString(service); |
| 80 | + return omitHttps ? stripHttps(url) : url; |
| 81 | + } catch (JSONException e) { |
| 82 | + throw new IllegalStateException("Malformed regions.json: " + e.getMessage(), e); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + public static Map<String, String> getAllEndpoints(String region) { |
| 87 | + return getAllEndpoints(region, false); |
| 88 | + } |
| 89 | + |
| 90 | + public static Map<String, String> getAllEndpoints(String region, boolean omitHttps) { |
| 91 | + if (region == null || region.trim().isEmpty()) { |
| 92 | + throw new IllegalArgumentException("Empty region provided. Please provide a valid region."); |
| 93 | + } |
| 94 | + JSONObject regionRow = resolveRegion(region); |
| 95 | + try { |
| 96 | + JSONObject endpoints = regionRow.getJSONObject("endpoints"); |
| 97 | + Map<String, String> result = new LinkedHashMap<>(); |
| 98 | + Iterator<String> keys = endpoints.keys(); |
| 99 | + while (keys.hasNext()) { |
| 100 | + String key = keys.next(); |
| 101 | + String url = endpoints.getString(key); |
| 102 | + result.put(key, omitHttps ? stripHttps(url) : url); |
| 103 | + } |
| 104 | + return result; |
| 105 | + } catch (JSONException e) { |
| 106 | + throw new IllegalStateException("Malformed regions.json: " + e.getMessage(), e); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + static synchronized void resetCache() { |
| 111 | + regionsCache = null; |
| 112 | + liveRefreshDone = false; |
| 113 | + } |
| 114 | + |
| 115 | + private static JSONObject resolveRegion(String region) { |
| 116 | + JSONArray regions = loadRegions(); |
| 117 | + try { |
| 118 | + return findRegion(regions, region); |
| 119 | + } catch (IllegalArgumentException notInBundled) { |
| 120 | + if (!liveRefreshDone) { |
| 121 | + JSONArray fresh = tryLiveRefresh(); |
| 122 | + if (fresh != null) { |
| 123 | + try { |
| 124 | + return findRegion(fresh, region); |
| 125 | + } catch (IllegalArgumentException ignored) { |
| 126 | + // fall through to re-throw the original error below |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + throw notInBundled; |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + private static synchronized JSONArray loadRegions() { |
| 135 | + if (regionsCache != null) { |
| 136 | + return regionsCache; |
| 137 | + } |
| 138 | + InputStream stream = Endpoint.class.getResourceAsStream("/assets/regions.json"); |
| 139 | + if (stream != null) { |
| 140 | + try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) { |
| 141 | + String raw = scanner.useDelimiter("\\A").next(); |
| 142 | + JSONObject root = new JSONObject(raw); |
| 143 | + regionsCache = root.getJSONArray("regions"); |
| 144 | + return regionsCache; |
| 145 | + } catch (JSONException e) { |
| 146 | + throw new IllegalStateException("Bundled regions.json is corrupt: " + e.getMessage(), e); |
| 147 | + } |
| 148 | + } |
| 149 | + logger.warning("Bundled regions.json not found in classpath — attempting live download."); |
| 150 | + JSONArray downloaded = tryLiveRefresh(); |
| 151 | + if (downloaded != null) { |
| 152 | + return downloaded; |
| 153 | + } |
| 154 | + throw new IllegalStateException( |
| 155 | + "regions.json not found in classpath and could not be downloaded from " |
| 156 | + + REGIONS_URL + ". Ensure the SDK was built correctly, or check network access."); |
| 157 | + } |
| 158 | + |
| 159 | + private static synchronized JSONArray tryLiveRefresh() { |
| 160 | + if (liveRefreshDone) { |
| 161 | + return regionsCache; |
| 162 | + } |
| 163 | + liveRefreshDone = true; |
| 164 | + try { |
| 165 | + logger.info("Refreshing regions from " + REGIONS_URL); |
| 166 | + URL url = new URL(REGIONS_URL); |
| 167 | + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); |
| 168 | + conn.setRequestMethod("GET"); |
| 169 | + conn.setConnectTimeout(5_000); |
| 170 | + conn.setReadTimeout(10_000); |
| 171 | + conn.setRequestProperty("Accept", "application/json"); |
| 172 | + try (InputStream stream = conn.getInputStream(); |
| 173 | + Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) { |
| 174 | + String raw = scanner.useDelimiter("\\A").next(); |
| 175 | + JSONObject root = new JSONObject(raw); |
| 176 | + regionsCache = root.getJSONArray("regions"); |
| 177 | + logger.info("regions.json refreshed from live URL (" + regionsCache.length() + " regions)."); |
| 178 | + return regionsCache; |
| 179 | + } |
| 180 | + } catch (Exception e) { |
| 181 | + logger.warning("Live region refresh failed: " + e.getMessage()); |
| 182 | + return null; |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + private static JSONObject findRegion(JSONArray regions, String region) { |
| 187 | + String normalized = region.trim().toLowerCase().replace('_', '-'); |
| 188 | + |
| 189 | + try { |
| 190 | + for (int i = 0; i < regions.length(); i++) { |
| 191 | + JSONObject row = regions.getJSONObject(i); |
| 192 | + if (row.getString("id").equals(normalized)) { |
| 193 | + return row; |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + for (int i = 0; i < regions.length(); i++) { |
| 198 | + JSONObject row = regions.getJSONObject(i); |
| 199 | + JSONArray aliases = row.optJSONArray("alias"); |
| 200 | + if (aliases == null) { |
| 201 | + continue; |
| 202 | + } |
| 203 | + for (int j = 0; j < aliases.length(); j++) { |
| 204 | + String alias = aliases.getString(j).toLowerCase().replace('_', '-'); |
| 205 | + if (alias.equals(normalized)) { |
| 206 | + return row; |
| 207 | + } |
| 208 | + } |
| 209 | + } |
| 210 | + } catch (JSONException e) { |
| 211 | + throw new IllegalStateException("Malformed regions.json: " + e.getMessage(), e); |
| 212 | + } |
| 213 | + |
| 214 | + throw new IllegalArgumentException("Invalid region: " + region); |
| 215 | + } |
| 216 | + |
| 217 | + private static String stripHttps(String url) { |
| 218 | + return url.replaceFirst("^https?://", ""); |
| 219 | + } |
| 220 | +} |
0 commit comments