Skip to content

Commit

Permalink
configuration may not have values for the given key
Browse files Browse the repository at this point in the history
  • Loading branch information
tomcz committed Sep 3, 2012
1 parent a8b2371 commit 47c705a
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 9 deletions.
4 changes: 3 additions & 1 deletion src/main/java/example/framework/Configuration.java
@@ -1,5 +1,7 @@
package example.framework;

import com.google.common.base.Optional;

public interface Configuration {
String get(String key);
Optional<String> get(String key);
}
Expand Up @@ -53,7 +53,7 @@ private String getConfiguredProperty(PicoContainer container) {
if (configuration == null) {
throw new IllegalStateException("Cannot find Configuration instance in container");
}
String value = configuration.get(key);
String value = configuration.get(key).orNull();
if (value == null) {
value = defaultValue;
}
Expand Down
@@ -1,7 +1,8 @@
package example.framework.application;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import example.framework.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrSubstitutor;

import java.util.HashMap;
Expand All @@ -25,8 +26,12 @@ private static Map createTokensToSubstitute(Map<String, String> properties) {
return tokens;
}

public String get(String key) {
String value = properties.get(key);
return StringUtils.isNotBlank(value) ? substitutor.replace(value) : value;
public Optional<String> get(String key) {
Optional<String> optional = Optional.fromNullable(properties.get(key));
return optional.transform(new Function<String, String>() {
public String apply(String value) {
return substitutor.replace(value).trim();
}
});
}
}
@@ -1,5 +1,6 @@
package example.framework.application;

import com.google.common.base.Optional;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Test;

Expand All @@ -19,7 +20,7 @@ public void shouldSubstituteSystemPropertiesAndTokensFromConfiguration() {
properties.put("foo", "bar");

DefaultConfiguration configuration = new DefaultConfiguration(properties);
String value = configuration.get("foo.path");
String value = configuration.get("foo.path").get();

assertThat(value, is(SystemUtils.USER_DIR + "/bar"));
}
Expand All @@ -29,8 +30,8 @@ public void shouldReturnNullForUnknownKey() {
Map<String, String> properties = newHashMap();

DefaultConfiguration configuration = new DefaultConfiguration(properties);
String value = configuration.get("foo");
Optional<String> value = configuration.get("foo");

assertThat(value, nullValue());
assertThat(value.orNull(), nullValue());
}
}

0 comments on commit 47c705a

Please sign in to comment.