Skip to content

Commit

Permalink
Support @WithConverter in Optional
Browse files Browse the repository at this point in the history
  • Loading branch information
radcortez committed Dec 20, 2022
1 parent 060d26c commit 36ea6ca
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ public static final class LeafProperty extends MayBeOptionalProperty {
super(method, propertyName);
this.valueType = valueType;
this.convertWith = convertWith;
rawType = rawTypeOf(valueType);
this.rawType = rawTypeOf(valueType);
this.defaultValue = defaultValue;
}

Expand Down Expand Up @@ -768,18 +768,19 @@ private static Property getPropertyDef(Method method, AnnotatedType type) {
// fall out (leaf)
}

WithDefault annotation = method.getAnnotation(WithDefault.class);
String defaultValue = annotation == null ? null : annotation.value();
if (rawType == List.class || rawType == Set.class) {
Type elementType = typeOfParameter(type.getType(), 0);
WithDefault annotation = method.getAnnotation(WithDefault.class);
return new CollectionProperty(rawType,
new LeafProperty(method, propertyName, elementType, convertWith,
annotation == null ? null : annotation.value()));
new LeafProperty(method, propertyName, elementType, convertWith, defaultValue));
} else if (rawType == Optional.class) {
return new OptionalProperty(method, propertyName,
new LeafProperty(method, propertyName, type.getType(), convertWith, defaultValue));
}

// otherwise it's a leaf
WithDefault annotation = method.getAnnotation(WithDefault.class);
return new LeafProperty(method, propertyName, type.getType(), convertWith,
annotation == null ? null : annotation.value());
return new LeafProperty(method, propertyName, type.getType(), convertWith, defaultValue);
}

private static boolean isToStringMethod(Method method) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1788,4 +1788,39 @@ interface Value {
String value();
}
}

@Test
void optionalWithConverter() {
SmallRyeConfig config = new SmallRyeConfigBuilder()
.addDefaultInterceptors()
.withMapping(OptionalWithConverter.class)
.withSources(config("optional.converter.value", "value"))
.build();

OptionalWithConverter mapping = config.getConfigMapping(OptionalWithConverter.class);

assertTrue(mapping.value().isPresent());
assertEquals("value", mapping.value().get().value);
}

@ConfigMapping(prefix = "optional.converter")
interface OptionalWithConverter {
@WithConverter(ValueConverter.class)
Optional<Value> value();
}

public static class ValueConverter implements Converter<Value> {
@Override
public Value convert(final String value) throws IllegalArgumentException, NullPointerException {
return new Value(value);
}
}

static class Value {
String value;

Value(final String value) {
this.value = value;
}
}
}

0 comments on commit 36ea6ca

Please sign in to comment.