Skip to content

Instantly share code, notes, and snippets.

@chaudum
Created August 29, 2014 12:29
Show Gist options
  • Save chaudum/ac1e91f17899d7e4f160 to your computer and use it in GitHub Desktop.
Save chaudum/ac1e91f17899d7e4f160 to your computer and use it in GitHub Desktop.
package io.crate.metadata.settings;
import com.google.common.collect.Sets;
import org.junit.Test;
import static org.junit.Assert.*;
public class CrateSettingsTest {
@Test
public void testStringSettingsValidation() throws Exception {
StringSetting stringSetting = new StringSetting(
Sets.newHashSet("foo", "bar", "foobar")
) {
@Override
public String name() { return "foo_bar_setting"; }
@Override
public String defaultValue() { return "foo"; }
};
String validation = stringSetting.validate("foo");
assertEquals(validation, null);
validation = stringSetting.validate("unknown");
assertEquals(validation, "'unknown' is not an allowed value. Allowed values are: bar, foo, foobar");
}
// ... more tests here ...
}
package io.crate.metadata.settings;
import com.google.common.base.Joiner;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import java.util.Set;
public abstract class StringSetting extends Setting<String> {
protected Set<String> allowedValues;
protected StringSetting(Set<String> allowedValues) {
this.allowedValues = allowedValues;
}
@Override
public String defaultValue() {
return "";
}
@Override
public String extract(Settings settings) {
return settings.get(settingName(), defaultValue());
}
/**
* @return Error message if not valid, else null.
*/
@Nullable
public String validate(String value) {
if (allowedValues != null && !allowedValues.contains(value)) {
return String.format("'%s' is not an allowed value. Allowed values are: %s",
value, Joiner.on(", ").join(allowedValues)
);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment