|
| 1 | +package com.auth0.telemetry; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | +import java.nio.charset.StandardCharsets; |
| 6 | +import java.util.Properties; |
| 7 | + |
| 8 | +/** |
| 9 | + * Provides the Base64-encoded Auth0-Client telemetry header value. |
| 10 | + * |
| 11 | + * The payload is a JSON object: {"name":"springboot-api","version":"x.y.z","java":"17"} |
| 12 | + */ |
| 13 | +public final class TelemetryProvider { |
| 14 | + |
| 15 | + private static final String PROPERTIES_FILE = "auth0-client-info.properties"; |
| 16 | + private static final String UNKNOWN = "unknown"; |
| 17 | + |
| 18 | + private static volatile String cachedHeaderValue; |
| 19 | + |
| 20 | + private TelemetryProvider() { |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Returns the Base64url-encoded telemetry header value. |
| 25 | + * |
| 26 | + * @return the Auth0-Client header value, or null if it cannot be built |
| 27 | + */ |
| 28 | + public static String getHeaderValue() { |
| 29 | + if (cachedHeaderValue != null) { |
| 30 | + return cachedHeaderValue; |
| 31 | + } |
| 32 | + synchronized (TelemetryProvider.class) { |
| 33 | + if (cachedHeaderValue != null) { |
| 34 | + return cachedHeaderValue; |
| 35 | + } |
| 36 | + cachedHeaderValue = buildHeaderValue(); |
| 37 | + return cachedHeaderValue; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private static String buildHeaderValue() { |
| 42 | + String name = UNKNOWN; |
| 43 | + String version = UNKNOWN; |
| 44 | + |
| 45 | + try (InputStream is = TelemetryProvider.class.getClassLoader() |
| 46 | + .getResourceAsStream(PROPERTIES_FILE)) { |
| 47 | + if (is != null) { |
| 48 | + Properties props = new Properties(); |
| 49 | + props.load(is); |
| 50 | + name = props.getProperty("name", UNKNOWN); |
| 51 | + version = props.getProperty("version", UNKNOWN); |
| 52 | + } |
| 53 | + } catch (IOException ignored) { |
| 54 | + // Fall through with defaults |
| 55 | + } |
| 56 | + |
| 57 | + String javaVersion = System.getProperty("java.version", UNKNOWN); |
| 58 | + |
| 59 | + String json = "{\"name\":\"" + name + "\",\"version\":\"" + version + "\",\"java\":\"" + javaVersion + "\"}"; |
| 60 | + |
| 61 | + return java.util.Base64.getUrlEncoder().withoutPadding() |
| 62 | + .encodeToString(json.getBytes(StandardCharsets.UTF_8)); |
| 63 | + } |
| 64 | +} |
0 commit comments