cloud.eppo.rac.dto.EppoAttributes Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sdk-common-jvm Show documentation
Show all versions of sdk-common-jvm Show documentation
Eppo SDK for JVM shared library
package cloud.eppo.rac.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.HashMap;
import java.util.Map;
/** Subject Attributes Class */
public class EppoAttributes extends HashMap {
public EppoAttributes() {
super();
}
public EppoAttributes(Map initialValues) {
super(initialValues);
}
public String serializeToJSONString() {
return EppoAttributes.serializeAttributesToJSONString(this);
}
public static String serializeAttributesToJSONString(Map attributes) {
return EppoAttributes.serializeAttributesToJSONString(attributes, false);
}
public static String serializeNonNullAttributesToJSONString(Map attributes) {
return EppoAttributes.serializeAttributesToJSONString(attributes, true);
}
private static String serializeAttributesToJSONString(
Map attributes, boolean omitNulls) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode result = mapper.createObjectNode();
for (Map.Entry entry : attributes.entrySet()) {
String attributeName = entry.getKey();
Object attributeValue = entry.getValue();
if (attributeValue instanceof EppoValue) {
EppoValue eppoValue = (EppoValue) attributeValue;
if (eppoValue.isNull()) {
if (!omitNulls) {
result.putNull(attributeName);
}
continue;
}
if (eppoValue.isNumeric()) {
result.put(attributeName, eppoValue.doubleValue());
continue;
}
if (eppoValue.isBoolean()) {
result.put(attributeName, eppoValue.boolValue());
continue;
}
// fall back put treating any other eppo values as a string
result.put(attributeName, eppoValue.toString());
} else if (attributeValue instanceof Double) {
Double doubleValue = (Double) attributeValue;
result.put(attributeName, doubleValue);
} else if (attributeValue == null) {
if (!omitNulls) {
result.putNull(attributeName);
}
} else {
// treat everything else as a string
result.put(attributeName, attributeValue.toString());
}
}
try {
return mapper.writeValueAsString(result);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}