Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
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");
map.put("key", context.getFullyQualifiedKey());
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));
}
}
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;
}
}
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;

/**
* 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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
package com.launchdarkly.sdk;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

import java.util.List;
import java.util.Map;

import org.junit.Test;

@SuppressWarnings("javadoc")
public class LDContextEncoderTest extends BaseTest {
@Test
public void nullContextReturnsEmptyMap() {
Map<String, Object> result = LDContextEncoder.encode(null);
assertThat(result.isEmpty(), is(true));
}

@Test
public void invalidContextReturnsEmptyMap() {
LDContext invalid = LDContext.create("");
assertThat(invalid.isValid(), is(false));
assertThat(LDContextEncoder.encode(invalid).isEmpty(), is(true));
}

@Test
public void singleKindContextIncludesKindKeyAndAnonymous() {
LDContext context = LDContext.builder("user-key").build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.get("kind"), is((Object) "user"));
assertThat(result.get("key"), is((Object) "user-key"));
assertThat(result.containsKey("anonymous"), is(true));
assertThat(result.get("anonymous"), is((Object) Boolean.FALSE));
}

@Test
public void singleKindContextIncludesNameWhenPresent() {
LDContext context = LDContext.builder("user-key").name("Bob").build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.get("name"), is((Object) "Bob"));
}

@Test
public void singleKindContextOmitsNameWhenNull() {
LDContext context = LDContext.builder("user-key").build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.containsKey("name"), is(false));
}

@Test
public void anonymousAlwaysPresentEvenWhenFalse() {
LDContext context = LDContext.builder("key").anonymous(false).build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.containsKey("anonymous"), is(true));
assertThat(result.get("anonymous"), is((Object) Boolean.FALSE));
}

@Test
public void anonymousTrueIsPresentWhenSet() {
LDContext context = LDContext.builder("key").anonymous(true).build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.get("anonymous"), is((Object) Boolean.TRUE));
}

@Test
public void singleKindContextIncludesCustomAttributes() {
LDContext context = LDContext.builder("user-key")
.set("tier", "gold")
.set("score", 42)
.build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.get("tier"), is((Object) "gold"));
assertThat(result.get("score"), is((Object) 42L));
}

@Test
public void customAttributeObjectValueIsDecoded() {
LDContext context = LDContext.builder("user-key")
.set("address", LDValue.buildObject().put("city", "Oakland").build())
.build();
Map<String, Object> result = LDContextEncoder.encode(context);
@SuppressWarnings("unchecked")
Map<String, Object> address = (Map<String, Object>) result.get("address");
assertThat(address, is(not(nullValue())));
assertThat(address.get("city"), is((Object) "Oakland"));
}

@Test
public void customAttributeArrayValueIsDecoded() {
LDContext context = LDContext.builder("user-key")
.set("tags", LDValue.buildArray().add("a").add("b").build())
.build();
Map<String, Object> result = LDContextEncoder.encode(context);
@SuppressWarnings("unchecked")
List<Object> tags = (List<Object>) result.get("tags");
assertThat(tags, is(not(nullValue())));
assertThat(tags.get(0), is((Object) "a"));
assertThat(tags.get(1), is((Object) "b"));
}

@Test
public void multiKindContextHasKindMultiAndFullyQualifiedKey() {
LDContext multi = LDContext.createMulti(
LDContext.builder("user-key").build(),
LDContext.builder(ContextKind.of("org"), "org-key").build());
Map<String, Object> result = LDContextEncoder.encode(multi);
assertThat(result.get("kind"), is((Object) "multi"));
assertThat(result.get("key"), is((Object) multi.getFullyQualifiedKey()));
}

@Test
public void multiKindContextContainsPerKindObjects() {
LDContext multi = LDContext.createMulti(
LDContext.builder("user-key").name("Bob").build(),
LDContext.builder(ContextKind.of("org"), "org-key").set("tier", "gold").build());
Map<String, Object> result = LDContextEncoder.encode(multi);

@SuppressWarnings("unchecked")
Map<String, Object> userMap = (Map<String, Object>) result.get("user");
assertThat(userMap, is(not(nullValue())));
assertThat(userMap.get("key"), is((Object) "user-key"));
assertThat(userMap.get("name"), is((Object) "Bob"));

@SuppressWarnings("unchecked")
Map<String, Object> orgMap = (Map<String, Object>) result.get("org");
assertThat(orgMap, is(not(nullValue())));
assertThat(orgMap.get("key"), is((Object) "org-key"));
assertThat(orgMap.get("tier"), is((Object) "gold"));
}

@Test
public void multiKindPerKindObjectsOmitKind() {
LDContext multi = LDContext.createMulti(
LDContext.builder("user-key").build(),
LDContext.builder(ContextKind.of("org"), "org-key").build());
Map<String, Object> result = LDContextEncoder.encode(multi);

@SuppressWarnings("unchecked")
Map<String, Object> userMap = (Map<String, Object>) result.get("user");
assertThat(userMap.containsKey("kind"), is(false));

@SuppressWarnings("unchecked")
Map<String, Object> orgMap = (Map<String, Object>) result.get("org");
assertThat(orgMap.containsKey("kind"), is(false));
}

@Test
public void multiKindNestedContextsIncludeAnonymous() {
LDContext multi = LDContext.createMulti(
LDContext.builder("user-key").build(),
LDContext.builder(ContextKind.of("org"), "org-key").anonymous(true).build());
Map<String, Object> result = LDContextEncoder.encode(multi);

@SuppressWarnings("unchecked")
Map<String, Object> userMap = (Map<String, Object>) result.get("user");
assertThat(userMap.containsKey("anonymous"), is(true));
assertThat(userMap.get("anonymous"), is((Object) Boolean.FALSE));

@SuppressWarnings("unchecked")
Map<String, Object> orgMap = (Map<String, Object>) result.get("org");
assertThat(orgMap.get("anonymous"), is((Object) Boolean.TRUE));
}

@Test
public void multiKindNestedContextIncludesNameOnlyWhenPresent() {
LDContext multi = LDContext.createMulti(
LDContext.builder("user-key").name("Alice").build(),
LDContext.builder(ContextKind.of("device"), "device-key").build());
Map<String, Object> result = LDContextEncoder.encode(multi);

@SuppressWarnings("unchecked")
Map<String, Object> userMap = (Map<String, Object>) result.get("user");
assertThat(userMap.get("name"), is((Object) "Alice"));

@SuppressWarnings("unchecked")
Map<String, Object> deviceMap = (Map<String, Object>) result.get("device");
assertThat(deviceMap.containsKey("name"), is(false));
}

@Test
public void customKindContextIsEncoded() {
LDContext context = LDContext.builder(ContextKind.of("device"), "device-123").build();
Map<String, Object> result = LDContextEncoder.encode(context);
assertThat(result.get("kind"), is((Object) "device"));
assertThat(result.get("key"), is((Object) "device-123"));
}

@Test
public void nestedObjectCustomAttributeIsDeeplyTraversable() {
LDContext context = LDContext.builder("user-key")
.set("meta", LDValue.buildObject()
.put("level1", LDValue.buildObject().put("level2", "deep-value").build())
.build())
.build();
Map<String, Object> result = LDContextEncoder.encode(context);
@SuppressWarnings("unchecked")
Map<String, Object> meta = (Map<String, Object>) result.get("meta");
@SuppressWarnings("unchecked")
Map<String, Object> level1 = (Map<String, Object>) meta.get("level1");
assertThat(level1.get("level2"), is((Object) "deep-value"));
}
}
Loading
Loading