Skip to content
Closed
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,6 @@
{
"type": "feature",
"category": "Amazon DynamoDB Enhanced Client",
"contributor": "",
"description": "Improve missing converter error handling in DynamoDB Enhanced Client"
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZoneIdAttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZoneOffsetAttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZonedDateTimeAsStringAttributeConverter;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;

Expand Down Expand Up @@ -157,17 +158,21 @@ private <T> Optional<AttributeConverter<T>> findConverterInternal(EnhancedType<T
return Optional.of(converter);
}

if (type.rawClass().isAssignableFrom(Map.class)) {
converter = createMapConverter(type);
} else if (type.rawClass().isAssignableFrom(Set.class)) {
converter = createSetConverter(type);
} else if (type.rawClass().isAssignableFrom(List.class)) {
EnhancedType<T> innerType = (EnhancedType<T>) type.rawClassParameters().get(0);
AttributeConverter<?> innerConverter = findConverter(innerType)
.orElseThrow(() -> new IllegalStateException("Converter not found for " + type));
return Optional.of((AttributeConverter<T>) ListAttributeConverter.create(innerConverter));
} else if (type.rawClass().isEnum()) {
return Optional.of(EnumAttributeConverter.create(((EnhancedType<? extends Enum>) type).rawClass()));
if (!Object.class.equals(type.rawClass())) {
if (type.rawClass().isAssignableFrom(Map.class)) {
requireTypeParameters(type);
converter = createMapConverter(type);
} else if (type.rawClass().isAssignableFrom(Set.class)) {
requireTypeParameters(type);
converter = createSetConverter(type);
} else if (type.rawClass().isAssignableFrom(List.class)) {
requireTypeParameters(type);
EnhancedType<T> innerType = (EnhancedType<T>) type.rawClassParameters().get(0);
AttributeConverter<?> innerConverter = converterFor(innerType, type);
return Optional.of((AttributeConverter<T>) ListAttributeConverter.create(innerConverter));
} else if (type.rawClass().isEnum()) {
return Optional.of(EnumAttributeConverter.create(((EnhancedType<? extends Enum>) type).rawClass()));
}
}

if (type.tableSchema().isPresent()) {
Expand All @@ -186,23 +191,42 @@ private boolean shouldCache(Class<?> type) {
return !type.isAnonymousClass();
}

private static void requireTypeParameters(EnhancedType<?> type) {
if (CollectionUtils.isNullOrEmpty(type.rawClassParameters())) {
throw new IllegalStateException("Converter not found for " + type + ". Type parameters are required for this type.");
}
}

private <T> AttributeConverter<T> converterFor(EnhancedType<T> type,
EnhancedType<?> containerType) {
return findConverter(type)
.orElseThrow(() -> converterNotFound(type, containerType));
}

private static IllegalStateException converterNotFound(EnhancedType<?> type,
EnhancedType<?> containerType) {
String elementOrValue = containerType.rawClass().isAssignableFrom(Map.class) ? "value" : "element";
return new IllegalStateException("Converter not found for " + type
+ " (" + elementOrValue + " of " + containerType + "). "
+ "DefaultAttributeConverterProvider resolves collection " + elementOrValue
+ " types only from its own converters.");
}

@SuppressWarnings("unchecked")
private <T> AttributeConverter<T> createMapConverter(EnhancedType<T> type) {
EnhancedType<?> keyType = type.rawClassParameters().get(0);
EnhancedType<T> valueType = (EnhancedType<T>) type.rawClassParameters().get(1);

StringConverter<?> keyConverter = StringConverterProvider.defaultProvider().converterFor(keyType);
AttributeConverter<?> valueConverter = findConverter(valueType)
.orElseThrow(() -> new IllegalStateException("Converter not found for " + type));
AttributeConverter<?> valueConverter = converterFor(valueType, type);

return (AttributeConverter<T>) MapAttributeConverter.mapConverter(keyConverter, valueConverter);
}

@SuppressWarnings("unchecked")
private <T> AttributeConverter<T> createSetConverter(EnhancedType<T> type) {
EnhancedType<T> innerType = (EnhancedType<T>) type.rawClassParameters().get(0);
AttributeConverter<?> innerConverter = findConverter(innerType)
.orElseThrow(() -> new IllegalStateException("Converter not found for " + type));
AttributeConverter<?> innerConverter = converterFor(innerType, type);

return (AttributeConverter<T>) SetAttributeConverter.setConverter(innerConverter);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
Expand Down Expand Up @@ -89,14 +90,18 @@ public static Builder builder() {
public static <T> AttributeConverter<T> converterForClass(EnhancedType<T> type,
ChainConverterProvider chainConverterProvider) {

if (type.rawClass().isAssignableFrom(List.class)) {
return (AttributeConverter<T>) ListAttributeConverter
.create(converterForClass(type.rawClassParameters().get(0), chainConverterProvider));
}
if (type.rawClass().isAssignableFrom(Map.class)) {
return (AttributeConverter<T>) MapAttributeConverter.mapConverter(
StringConverterProvider.defaultProvider().converterFor(type.rawClassParameters().get(0)),
converterForClass(type.rawClassParameters().get(1), chainConverterProvider));
if (!Object.class.equals(type.rawClass())) {
if (type.rawClass().isAssignableFrom(List.class)) {
requireTypeParameters(type);
return (AttributeConverter<T>) ListAttributeConverter
.create(converterForClass(type.rawClassParameters().get(0), chainConverterProvider));
}
if (type.rawClass().isAssignableFrom(Map.class)) {
requireTypeParameters(type);
return (AttributeConverter<T>) MapAttributeConverter.mapConverter(
StringConverterProvider.defaultProvider().converterFor(type.rawClassParameters().get(0)),
converterForClass(type.rawClassParameters().get(1), chainConverterProvider));
}
}
return Optional.ofNullable(chainConverterProvider.converterFor(type))
.orElseThrow(() -> new IllegalStateException(
Expand Down Expand Up @@ -496,4 +501,12 @@ private static void checkAndValidateClass(Class<?> type, boolean isPut) {
String.format(VALIDATE_TYPE_ERROR, "Map", isPut ? "put" : "get", "Map"));

}

private static void requireTypeParameters(EnhancedType<?> type) {
if (CollectionUtils.isNullOrEmpty(type.rawClassParameters())) {
throw new IllegalStateException(
"AttributeConverter not found for class " + type
+ ". Type parameters are required for this type.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,20 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.logging.log4j.core.LogEvent;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.event.Level;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;

public class DefaultAttributeConverterProviderTest {

Expand All @@ -47,8 +57,7 @@ void findConverter_whenConverterNotFound_logsNoConverter() {

assertThatThrownBy(() -> provider.converterFor(EnhancedType.of(CustomUnsupportedType.class)))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Converter not found for EnhancedType(software.amazon.awssdk.enhanced.dynamodb"
+ ".DefaultAttributeConverterProviderTest$CustomUnsupportedType)");
.hasMessage("Converter not found for " + EnhancedType.of(CustomUnsupportedType.class));
List<LogEvent> logEvents = logCaptor.loggedEvents();
assertThat(logEvents).hasSize(1);
assertThat(logEvents.get(0).getLevel().name()).isEqualTo(Level.DEBUG.name());
Expand All @@ -58,9 +67,179 @@ void findConverter_whenConverterNotFound_logsNoConverter() {
}
}

@ParameterizedTest
@MethodSource("unsupportedTypes")
void converterFor_whenUnsupportedType_throwsConverterNotFound(EnhancedType<?> type) {
DefaultAttributeConverterProvider provider = DefaultAttributeConverterProvider.create();

assertThatThrownBy(() -> provider.converterFor(type))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Converter not found for " + type);
}

@ParameterizedTest
@MethodSource("customConverters")
<T> void build_whenCustomProviderFirst_usesCustomConverter(AttributeConverter<T> converter) {
AttributeConverterProvider customProvider = new CustomAttributeConverterProvider(converter);
StaticTableSchema<Map<String, T>> schema =
schemaWithAttribute(converter.type())
.attributeConverterProviders(customProvider, DefaultAttributeConverterProvider.create())
.build();

assertThat(schema.converterForAttribute("value")).isSameAs(converter);
}

@ParameterizedTest
@MethodSource("rawCollectionTypes")
void findConverter_whenRawCollectionType_throwsConverterNotFound(EnhancedType<?> type) {
DefaultAttributeConverterProvider provider = DefaultAttributeConverterProvider.create();

assertThatThrownBy(() -> provider.converterFor(type))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Converter not found for " + type + ". Type parameters are required for this type.");
}

@ParameterizedTest
@MethodSource("unsupportedTypes")
void converterFor_whenMapValueHasNoConverter_throwsConverterNotFound(EnhancedType<?> valueType) {
DefaultAttributeConverterProvider provider = DefaultAttributeConverterProvider.create();
EnhancedType<?> type = EnhancedType.mapOf(EnhancedType.of(String.class), valueType);

assertThatThrownBy(() -> provider.converterFor(type))
.isInstanceOf(IllegalStateException.class)
.hasMessage(missingNestedConverterMessage(valueType, type, "value"));
}

@ParameterizedTest
@MethodSource("unsupportedTypes")
void converterFor_whenSetElementHasNoConverter_throwsConverterNotFound(EnhancedType<?> elementType) {
DefaultAttributeConverterProvider provider = DefaultAttributeConverterProvider.create();
EnhancedType<?> type = EnhancedType.setOf(elementType);

assertThatThrownBy(() -> provider.converterFor(type))
.isInstanceOf(IllegalStateException.class)
.hasMessage(missingNestedConverterMessage(elementType, type, "element"));
}

@ParameterizedTest
@MethodSource("unsupportedTypes")
void converterFor_whenListElementHasNoConverter_throwsConverterNotFound(EnhancedType<?> elementType) {
DefaultAttributeConverterProvider provider = DefaultAttributeConverterProvider.create();
EnhancedType<?> type = EnhancedType.listOf(elementType);

assertThatThrownBy(() -> provider.converterFor(type))
.isInstanceOf(IllegalStateException.class)
.hasMessage(missingNestedConverterMessage(elementType, type, "element"));
}

@Test
void build_whenSchemaAttributeIsObject_throwsConverterNotFound() {
EnhancedType<Object> type = EnhancedType.of(Object.class);

assertThatThrownBy(() -> schemaWithAttribute(type).build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Converter not found for " + type);
}

@ParameterizedTest
@MethodSource("collectionsWithObjectMembers")
void build_whenCollectionMemberIsObject_throwsConverterNotFound(EnhancedType<?> type, String role) {
assertThatThrownBy(() -> schemaWithAttribute(type).build())
.isInstanceOf(IllegalStateException.class)
.hasMessage(missingNestedConverterMessage(EnhancedType.of(Object.class), type, role));
}

private static Stream<Arguments> collectionsWithObjectMembers() {
return Stream.of(
Arguments.of(EnhancedType.listOf(Object.class), "element"),
Arguments.of(EnhancedType.setOf(Object.class), "element"),
Arguments.of(EnhancedType.mapOf(String.class, Object.class), "value"));
}

private static <T> StaticTableSchema.Builder<Map<String, T>> schemaWithAttribute(EnhancedType<T> attributeType) {
return StaticTableSchema.builder(EnhancedType.mapOf(EnhancedType.of(String.class), attributeType))
.newItemSupplier(HashMap::new)
.addAttribute(attributeType, a -> a.name("value")
.getter(item -> item.get("value"))
.setter((item, value) -> item.put("value", value)));
}

private static String missingNestedConverterMessage(EnhancedType<?> nestedType,
EnhancedType<?> collectionType,
String elementOrValue) {
return "Converter not found for " + nestedType
+ " (" + elementOrValue + " of " + collectionType + "). "
+ "DefaultAttributeConverterProvider resolves collection " + elementOrValue
+ " types only from its own converters.";
}

private static Stream<AttributeConverter<?>> customConverters() {
return Stream.of(new CustomStringConverter<>(EnhancedType.of(Object.class), Object::toString, value -> value),
new CustomStringConverter<>(EnhancedType.of(CustomUnsupportedType.class), value -> value.value,
CustomUnsupportedType::new));
}

private static Stream<EnhancedType<?>> unsupportedTypes() {
return Stream.of(EnhancedType.of(Object.class), EnhancedType.of(CustomUnsupportedType.class));
}

private static Stream<EnhancedType<?>> rawCollectionTypes() {
return Stream.of(EnhancedType.of(Map.class), EnhancedType.of(Set.class), EnhancedType.of(List.class));
}

private static final class CustomAttributeConverterProvider implements AttributeConverterProvider {
private final AttributeConverter<?> converter;

private CustomAttributeConverterProvider(AttributeConverter<?> converter) {
this.converter = converter;
}

@Override
public <T> AttributeConverter<T> converterFor(EnhancedType<T> type) {
return converter.type().equals(type) ? (AttributeConverter<T>) converter : null;
}
}

private static final class CustomStringConverter<T> implements AttributeConverter<T> {
private final EnhancedType<T> type;
private final Function<T, String> encoder;
private final Function<String, T> decoder;

private CustomStringConverter(EnhancedType<T> type, Function<T, String> encoder, Function<String, T> decoder) {
this.type = type;
this.encoder = encoder;
this.decoder = decoder;
}

@Override
public AttributeValue transformFrom(T input) {
return AttributeValue.fromS(encoder.apply(input));
}

@Override
public T transformTo(AttributeValue input) {
return decoder.apply(input.s());
}

@Override
public EnhancedType<T> type() {
return type;
}

@Override
public AttributeValueType attributeValueType() {
return AttributeValueType.S;
}
}

/**
* A custom type with no converter registered for it.
*/
private static class CustomUnsupportedType {
private final String value;

private CustomUnsupportedType(String value) {
this.value = value;
}
}
}
Loading
Loading