Skip to content
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

Add basic support for optionals #264

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
*/
package org.cfg4j.provider;

import static java.util.Objects.requireNonNull;

import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
Expand All @@ -26,10 +24,15 @@
import org.cfg4j.validator.BindingValidator;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Properties;

import static java.util.Objects.requireNonNull;

/**
* Basic implementation of {@link ConfigurationProvider}. To construct this provider use {@link ConfigurationProviderBuilder}.
*/
Expand Down Expand Up @@ -67,40 +70,57 @@ public <T> T getProperty(String key, Class<T> type) {
TypeParser parser = TypeParser.newBuilder().build();
return parser.parse(propertyStr, type);
} catch (TypeParserException | NoSuchRegisteredParserException e) {
throw new IllegalArgumentException("Unable to cast value \'" + propertyStr + "\' to " + type, e);
throw new IllegalArgumentException("Unable to cast value '" + propertyStr + "' to " + type, e);
}
}

@Override
public <T> T getProperty(String key, GenericTypeInterface genericType) {
boolean isOptional = isOptional(genericType);
if (isOptional && isMissingProperty(key)) {
@SuppressWarnings("unchecked")
T property = (T) Optional.empty();
return property;
}
String propertyStr = getProperty(key);

try {
TypeParser parser = TypeParser.newBuilder().build();
Object parsedProperty = TypeParser.newBuilder().build().parseType(propertyStr, getResolvedType(genericType));
@SuppressWarnings("unchecked")
T property = (T) parser.parseType(propertyStr, genericType.getType());
T property = (T) (isOptional ? Optional.of(parsedProperty) : parsedProperty);
return property;
} catch (TypeParserException | NoSuchRegisteredParserException e) {
throw new IllegalArgumentException("Unable to cast value \'" + propertyStr + "\' to " + genericType, e);
throw new IllegalArgumentException("Unable to cast value '" + propertyStr + "' to " + genericType, e);
}
}

private String getProperty(String key) {
try {

Object property = configurationSource.getConfiguration(environment).get(key);

if (property == null) {
throw new NoSuchElementException("No configuration with key: " + key);
}

return property.toString();
private boolean isOptional(GenericTypeInterface genericType) {
return genericType.getType() instanceof ParameterizedType && ((ParameterizedType) genericType.getType()).getRawType().equals(Optional.class);
}

private boolean isMissingProperty(String key) {
try {
return !configurationSource.getConfiguration(environment).containsKey(key);
} catch (IllegalStateException e) {
throw new IllegalStateException("Couldn't fetch configuration from configuration source for key: " + key, e);
}
}

private Type getResolvedType(GenericTypeInterface genericType) {
if (isOptional(genericType)) {
return ((ParameterizedType) genericType.getType()).getActualTypeArguments()[0];
} else {
return genericType.getType();
}
}

private String getProperty(String key) {
if (isMissingProperty(key)) {
throw new NoSuchElementException("No configuration with key: " + key);
}
Object property = configurationSource.getConfiguration(environment).get(key);
return property.toString();
}

@Override
public <T> T bind(String prefix, Class<T> type) {
return bind(this, prefix, type);
Expand Down Expand Up @@ -133,8 +153,8 @@ <T> T bind(ConfigurationProvider configurationProvider, String prefix, Class<T>
@Override
public String toString() {
return "SimpleConfigurationProvider{" +
"configurationSource=" + configurationSource +
", environment=" + environment +
'}';
"configurationSource=" + configurationSource +
", environment=" + environment +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Properties;


Expand All @@ -36,6 +37,10 @@ public interface MultiPropertyConfigPojo extends ConfigPojo {
List<Boolean> otherSetting();
}

public interface OptionalConfigPojo extends ConfigPojo {
Optional<String> otherSetting();
}

@Test
void bindThrowsWhenFetchingNonexistentKey() {
when(configurationSource.getConfiguration(anyEnvironment())).thenReturn(new Properties());
Expand Down Expand Up @@ -91,4 +96,23 @@ void reactsToSourceChanges() {

assertThat(config.someSetting()).isEqualTo(0);
}

@Test
void bindsOptionalWithValue() {
when(configurationSource.getConfiguration(anyEnvironment())).thenReturn(propertiesWith("someSetting", "42", "otherSetting", "string"));

OptionalConfigPojo config = simpleConfigurationProvider.bind("", OptionalConfigPojo.class);
assertThat(config.someSetting()).isEqualTo(42);
assertThat(config.otherSetting()).isNotEmpty();
assertThat(config.otherSetting()).containsSame("string");
}

@Test
void bindsOptionalWithoutValue() {
when(configurationSource.getConfiguration(anyEnvironment())).thenReturn(propertiesWith("someSetting", "42"));

OptionalConfigPojo config = simpleConfigurationProvider.bind("", OptionalConfigPojo.class);
assertThat(config.someSetting()).isEqualTo(42);
assertThat(config.otherSetting()).isEmpty();
}
}