|
| 1 | +package com.contentstack.utils; |
| 2 | + |
| 3 | +import org.json.JSONArray; |
| 4 | +import org.json.JSONException; |
| 5 | +import org.json.JSONObject; |
| 6 | + |
| 7 | +import java.io.BufferedReader; |
| 8 | +import java.io.IOException; |
| 9 | +import java.io.InputStream; |
| 10 | +import java.io.InputStreamReader; |
| 11 | +import java.net.HttpURLConnection; |
| 12 | +import java.net.URL; |
| 13 | +import java.nio.charset.StandardCharsets; |
| 14 | +import java.util.LinkedHashMap; |
| 15 | +import java.util.Map; |
| 16 | +import java.util.stream.Collectors; |
| 17 | + |
| 18 | +/** |
| 19 | + * Resolves Contentstack API endpoints for any region and service. |
| 20 | + * |
| 21 | + * <p>Endpoint data is loaded from the bundled {@code regions.json} resource. |
| 22 | + * The parsed result is cached for the lifetime of the JVM process. |
| 23 | + * If the bundled file is absent, a live download from |
| 24 | + * {@code https://artifacts.contentstack.com/regions.json} is attempted as a fallback. |
| 25 | + * |
| 26 | + * <pre>{@code |
| 27 | + * // Get a specific service URL |
| 28 | + * String cdnUrl = Endpoint.getContentstackEndpoint("eu", "contentDelivery"); |
| 29 | + * // → "https://eu-cdn.contentstack.com" |
| 30 | + * |
| 31 | + * // Get the host without the https:// scheme |
| 32 | + * String host = Endpoint.getContentstackEndpoint("eu", "contentDelivery", true); |
| 33 | + * // → "eu-cdn.contentstack.com" |
| 34 | + * |
| 35 | + * // Get all endpoints for a region |
| 36 | + * Map<String, String> all = Endpoint.getContentstackEndpoint("eu"); |
| 37 | + * }</pre> |
| 38 | + */ |
| 39 | +public class Endpoint { |
| 40 | + |
| 41 | + private static final String REGIONS_URL = "https://artifacts.contentstack.com/regions.json"; |
| 42 | + private static final String REGIONS_RESOURCE = "regions.json"; |
| 43 | + |
| 44 | + private static JSONArray regionsData = null; |
| 45 | + |
| 46 | + private Endpoint() {} |
| 47 | + |
| 48 | + /** |
| 49 | + * Returns the URL for a specific service in the given region. |
| 50 | + * |
| 51 | + * @param region canonical region ID ({@code na}, {@code eu}, {@code au}, {@code azure-na}, |
| 52 | + * {@code azure-eu}, {@code gcp-na}, {@code gcp-eu}) or any accepted alias. |
| 53 | + * Case-insensitive; {@code -} and {@code _} separators are equivalent. |
| 54 | + * @param service service name (e.g. {@code contentDelivery}, {@code contentManagement}) |
| 55 | + * @return full URL including {@code https://} |
| 56 | + * @throws IllegalArgumentException if region or service is unknown, or region is empty |
| 57 | + * @throws RuntimeException if {@code regions.json} cannot be loaded |
| 58 | + */ |
| 59 | + public static String getContentstackEndpoint(String region, String service) { |
| 60 | + return getContentstackEndpoint(region, service, false); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Returns the URL for a specific service in the given region. |
| 65 | + * |
| 66 | + * @param region canonical region ID or alias |
| 67 | + * @param service service name |
| 68 | + * @param omitHttps when {@code true}, strips {@code https://} from the result |
| 69 | + * @return URL string, with or without scheme depending on {@code omitHttps} |
| 70 | + * @throws IllegalArgumentException if region or service is unknown, or region is empty |
| 71 | + * @throws RuntimeException if {@code regions.json} cannot be loaded |
| 72 | + */ |
| 73 | + public static String getContentstackEndpoint(String region, String service, boolean omitHttps) { |
| 74 | + if (service == null || service.trim().isEmpty()) { |
| 75 | + throw new IllegalArgumentException("Service must not be empty. Use getContentstackEndpoint(region) to get all endpoints."); |
| 76 | + } |
| 77 | + JSONObject regionRow = resolveRegion(region); |
| 78 | + JSONObject endpoints = regionRow.getJSONObject("endpoints"); |
| 79 | + if (!endpoints.has(service)) { |
| 80 | + throw new IllegalArgumentException("Service \"" + service + "\" not found for region \"" + regionRow.getString("id") + "\""); |
| 81 | + } |
| 82 | + String url = endpoints.getString(service); |
| 83 | + return omitHttps ? stripHttps(url) : url; |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Returns all endpoint URLs for the given region as an ordered map. |
| 88 | + * |
| 89 | + * @param region canonical region ID or alias |
| 90 | + * @return map of service name → URL (includes {@code https://}) |
| 91 | + * @throws IllegalArgumentException if region is unknown or empty |
| 92 | + * @throws RuntimeException if {@code regions.json} cannot be loaded |
| 93 | + */ |
| 94 | + public static Map<String, String> getContentstackEndpoint(String region) { |
| 95 | + return getContentstackEndpoint(region, false); |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Returns all endpoint URLs for the given region as an ordered map. |
| 100 | + * |
| 101 | + * @param region canonical region ID or alias |
| 102 | + * @param omitHttps when {@code true}, strips {@code https://} from every URL |
| 103 | + * @return map of service name → URL |
| 104 | + * @throws IllegalArgumentException if region is unknown or empty |
| 105 | + * @throws RuntimeException if {@code regions.json} cannot be loaded |
| 106 | + */ |
| 107 | + public static Map<String, String> getContentstackEndpoint(String region, boolean omitHttps) { |
| 108 | + JSONObject regionRow = resolveRegion(region); |
| 109 | + JSONObject endpoints = regionRow.getJSONObject("endpoints"); |
| 110 | + Map<String, String> result = new LinkedHashMap<>(); |
| 111 | + for (String serviceName : endpoints.keySet()) { |
| 112 | + String url = endpoints.getString(serviceName); |
| 113 | + result.put(serviceName, omitHttps ? stripHttps(url) : url); |
| 114 | + } |
| 115 | + return result; |
| 116 | + } |
| 117 | + |
| 118 | + // ── internal ────────────────────────────────────────────────────────────── |
| 119 | + |
| 120 | + private static JSONObject resolveRegion(String region) { |
| 121 | + if (region == null || region.trim().isEmpty()) { |
| 122 | + throw new IllegalArgumentException("Empty region provided. Please provide a valid region."); |
| 123 | + } |
| 124 | + JSONArray regions = loadRegions(); |
| 125 | + String normalized = region.trim().toLowerCase().replace('_', '-'); |
| 126 | + |
| 127 | + // First pass: exact match on region id field |
| 128 | + for (int i = 0; i < regions.length(); i++) { |
| 129 | + JSONObject row = regions.getJSONObject(i); |
| 130 | + if (row.getString("id").equals(normalized)) { |
| 131 | + return row; |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + // Second pass: match on accepted alternate names (case-insensitive, normalised separators) |
| 136 | + for (int i = 0; i < regions.length(); i++) { |
| 137 | + JSONObject row = regions.getJSONObject(i); |
| 138 | + JSONArray alternateNames = row.getJSONArray("alias"); |
| 139 | + for (int j = 0; j < alternateNames.length(); j++) { |
| 140 | + String alternateName = alternateNames.getString(j).toLowerCase().replace('_', '-'); |
| 141 | + if (alternateName.equals(normalized)) { |
| 142 | + return row; |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + throw new IllegalArgumentException("Invalid region: " + region); |
| 148 | + } |
| 149 | + |
| 150 | + private static synchronized JSONArray loadRegions() { |
| 151 | + if (regionsData != null) { |
| 152 | + return regionsData; |
| 153 | + } |
| 154 | + |
| 155 | + // Try live download first so users always get the latest regions |
| 156 | + try { |
| 157 | + String json = downloadRegions(); |
| 158 | + regionsData = new JSONObject(json).getJSONArray("regions"); |
| 159 | + return regionsData; |
| 160 | + } catch (IOException | JSONException ignored) { |
| 161 | + // network unavailable — fall through to bundled fallback |
| 162 | + } |
| 163 | + |
| 164 | + // Fallback: bundled regions.json packaged in the JAR (offline safety net) |
| 165 | + InputStream is = Endpoint.class.getClassLoader().getResourceAsStream(REGIONS_RESOURCE); |
| 166 | + if (is != null) { |
| 167 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { |
| 168 | + String json = reader.lines().collect(Collectors.joining("\n")); |
| 169 | + regionsData = new JSONObject(json).getJSONArray("regions"); |
| 170 | + return regionsData; |
| 171 | + } catch (IOException | JSONException ignored) { |
| 172 | + // fall through to error |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + throw new RuntimeException( |
| 177 | + "contentstack/utils: could not load regions — network unavailable and no bundled fallback found."); |
| 178 | + } |
| 179 | + |
| 180 | + private static String downloadRegions() throws IOException { |
| 181 | + URL url = new URL(REGIONS_URL); |
| 182 | + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); |
| 183 | + conn.setRequestMethod("GET"); |
| 184 | + conn.setConnectTimeout(10000); |
| 185 | + conn.setReadTimeout(10000); |
| 186 | + try (InputStream is = conn.getInputStream(); |
| 187 | + BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { |
| 188 | + return reader.lines().collect(Collectors.joining("\n")); |
| 189 | + } finally { |
| 190 | + conn.disconnect(); |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + private static String stripHttps(String url) { |
| 195 | + return url.replaceAll("^https?://", ""); |
| 196 | + } |
| 197 | + |
| 198 | + /** Clears the in-memory cache. For use in tests only. */ |
| 199 | + static void resetCache() { |
| 200 | + regionsData = null; |
| 201 | + } |
| 202 | +} |
0 commit comments