-
Notifications
You must be signed in to change notification settings - Fork 12
feat: add LDValueConverter and LDContextEncoder to common #187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mattrmc1
wants to merge
2
commits into
main
Choose a base branch
from
mmccarthy/AIC-2939/add-context-encoder-to-common
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
73 changes: 73 additions & 0 deletions
73
lib/shared/common/src/main/java/com/launchdarkly/sdk/LDContextEncoder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| package com.launchdarkly.sdk; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * Encodes an {@link LDContext} into a plain nested {@code Map<String, Object>} structure without | ||
| * round-tripping through JSON serialization. Leaf attribute values are converted by | ||
| * {@link LDValueConverter}. | ||
| * <p> | ||
| * Output shape: | ||
| * <ul> | ||
| * <li>A {@code null} or invalid context produces an empty map.</li> | ||
| * <li>A single-kind context produces a map containing {@code kind}, {@code key}, | ||
| * {@code name} (only when non-null), {@code anonymous} (always present), and one entry for | ||
| * each custom attribute.</li> | ||
| * <li>A multi-kind context produces | ||
| * {@code {"kind":"multi", "key":<fullyQualifiedKey>, <kindName>:{...}, ...}} where each | ||
| * per-kind nested map omits {@code kind} (it is implied by the property key).</li> | ||
| * </ul> | ||
| */ | ||
| public final class LDContextEncoder { | ||
|
|
||
| private LDContextEncoder() { | ||
| } | ||
|
|
||
| /** | ||
| * Encodes an {@link LDContext} into a plain nested {@code Map<String, Object>}. | ||
| * | ||
| * @param context the context to encode; may be {@code null} | ||
| * @return the encoded map; never {@code null} (an empty map is returned for invalid or null input) | ||
| */ | ||
| public static Map<String, Object> encode(LDContext context) { | ||
| if (context == null || !context.isValid()) { | ||
| return new HashMap<>(); | ||
| } | ||
| if (context.isMultiple()) { | ||
| Map<String, Object> map = new HashMap<>(); | ||
| map.put("kind", "multi"); | ||
| int count = context.getIndividualContextCount(); | ||
| for (int i = 0; i < count; i++) { | ||
| LDContext individual = context.getIndividualContext(i); | ||
| if (individual != null) { | ||
| // Mirror LaunchDarkly's standard context JSON: per-kind objects nested under a | ||
| // multi-kind context omit "kind" because it is already implied by the property key. | ||
| map.put(individual.getKind().toString(), encodeSingle(individual, false)); | ||
| } | ||
| } | ||
| // Written after the loop so it always wins, even if a member kind is named "key". | ||
| map.put("key", context.getFullyQualifiedKey()); | ||
| return map; | ||
| } | ||
| return encodeSingle(context, true); | ||
| } | ||
|
|
||
| private static Map<String, Object> encodeSingle(LDContext context, boolean includeKind) { | ||
| Map<String, Object> map = new HashMap<>(); | ||
| if (includeKind) { | ||
| map.put("kind", context.getKind().toString()); | ||
| } | ||
| map.put("key", context.getKey()); | ||
| if (context.getName() != null) { | ||
| map.put("name", context.getName()); | ||
| } | ||
| map.put("anonymous", context.isAnonymous()); | ||
| // Custom attribute values can be arbitrary JSON; convert each LDValue to a plain Java value | ||
| // (depth-capped) so nested objects/arrays are fully traversable. | ||
| for (String attribute : context.getCustomAttributeNames()) { | ||
| map.put(attribute, LDValueConverter.toJavaObject(context.getValue(attribute))); | ||
| } | ||
| return map; | ||
| } | ||
| } | ||
111 changes: 111 additions & 0 deletions
111
lib/shared/common/src/main/java/com/launchdarkly/sdk/LDValueConverter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| package com.launchdarkly.sdk; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * Converts an {@link LDValue} tree into a tree of plain Java values | ||
| * ({@link String}, {@link Long}, {@link Double}, {@link Boolean}, {@link List}, {@link Map}, or | ||
| * {@code null}). | ||
| * <p> | ||
| * Conversion is defensive: it never throws on malformed or pathological input. Numbers are decoded | ||
| * to {@link Long} when they are mathematically integral and within the IEEE-754 exact-integer range | ||
| * ({@code |value| <= 2^53}); otherwise they are decoded to {@link Double}. Whole numbers outside | ||
| * {@code ±2^53} cannot be represented exactly and are returned as the nearest {@link Double}. | ||
| * Conversion depth is capped (see {@link #MAX_DEPTH}); values nested more deeply than the cap are | ||
| * dropped (rendered as {@code null}) to bound stack usage on adversarial input. | ||
| * <p> | ||
| * Object fields are stored in a {@link LinkedHashMap} to preserve insertion order, and all | ||
| * returned collections are unmodifiable. | ||
| */ | ||
| public final class LDValueConverter { | ||
| /** | ||
| * Maximum nesting depth converted before deeper values are dropped. | ||
| */ | ||
| public static final int MAX_DEPTH = 100; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Where does this come from? |
||
|
|
||
| /** | ||
| * Largest magnitude of a whole number that a {@code double} can represent exactly. | ||
| */ | ||
| private static final double MAX_EXACT_INTEGER = 9007199254740992.0; // 2^53 | ||
|
|
||
| private LDValueConverter() { | ||
| } | ||
|
|
||
| /** | ||
| * Converts an {@link LDValue} to a plain Java value. | ||
| * | ||
| * @param value the value to convert; may be {@code null} | ||
| * @return the converted value, or {@code null} if the input is {@code null} or JSON null | ||
| */ | ||
| public static Object toJavaObject(LDValue value) { | ||
| return convert(value, 0); | ||
| } | ||
|
|
||
| /** | ||
| * Converts an {@link LDValue} object to an unmodifiable {@code Map<String, Object>}. | ||
| * | ||
| * @param value the value to convert | ||
| * @return the converted map; {@code null} if {@code value} is not a JSON object | ||
| */ | ||
| public static Map<String, Object> toMap(LDValue value) { | ||
| if (value == null || value.getType() != LDValueType.OBJECT) { | ||
| return null; | ||
| } | ||
| Object converted = convert(value, 0); | ||
| if (converted instanceof Map) { | ||
| @SuppressWarnings("unchecked") | ||
| Map<String, Object> map = (Map<String, Object>) converted; | ||
| return map; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| private static Object convert(LDValue value, int depth) { | ||
| if (value == null || value.isNull()) { | ||
| return null; | ||
| } | ||
| if (depth >= MAX_DEPTH) { | ||
| return null; | ||
| } | ||
|
|
||
| LDValueType type = value.getType(); | ||
| switch (type) { | ||
| case BOOLEAN: | ||
| return value.booleanValue(); | ||
| case NUMBER: | ||
| return convertNumber(value.doubleValue()); | ||
| case STRING: | ||
| return value.stringValue(); | ||
| case ARRAY: { | ||
| List<Object> list = new ArrayList<>(value.size()); | ||
| for (LDValue element : value.values()) { | ||
| list.add(convert(element, depth + 1)); | ||
| } | ||
| return Collections.unmodifiableList(list); | ||
| } | ||
| case OBJECT: { | ||
| // LinkedHashMap to preserve field order for deterministic output. | ||
| Map<String, Object> map = new LinkedHashMap<>(); | ||
| for (String key : value.keys()) { | ||
| map.put(key, convert(value.get(key), depth + 1)); | ||
| } | ||
| return Collections.unmodifiableMap(map); | ||
| } | ||
| case NULL: | ||
| default: | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| private static Object convertNumber(double d) { | ||
| if (!Double.isNaN(d) && !Double.isInfinite(d) | ||
| && d == Math.rint(d) && Math.abs(d) <= MAX_EXACT_INTEGER) { | ||
| return (long) d; | ||
| } | ||
| return d; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.