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

CORE: Validate Type for String Settings #33503

Merged
merged 5 commits into from
Sep 10, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Expand Up @@ -19,6 +19,7 @@

package org.elasticsearch.common.settings;

import java.util.Collection;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
Expand Down Expand Up @@ -385,6 +386,16 @@ private T get(Settings settings, boolean validate) {
try {
T parsed = parser.apply(value);
if (validate) {
if (parsed instanceof String) {
Class<?> rawValueClass = settings.getRawType(getKey());
if (rawValueClass != null
&& (Map.class.isAssignableFrom(rawValueClass) || Collection.class.isAssignableFrom(rawValueClass))
) {
throw new IllegalArgumentException(
"Failed to parse [" + value + "] for string setting [" + getKey() + "] because it is not scalar."
);
}
}
final Iterator<Setting<T>> it = validator.settings();
final Map<Setting<T>, T> map;
if (it.hasNext()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,11 @@ public String get(String setting, String defaultValue) {
return retVal == null ? defaultValue : retVal;
}

Class<?> getRawType(String setting) {
Object value = settings.get(setting);
return value == null ? null : value.getClass();
}

/**
* Returns the setting value (as float) associated with the setting key. If it does not exists,
* returns the default value provided.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ public void testSimpleUpdate() {
}
}

public void testValidateStringSetting() {
Settings settings = Settings.builder().putList("foo.bar", Arrays.asList("bla-a", "bla-b")).build();
Setting<String> stringSetting = Setting.simpleString("foo.bar", Property.NodeScope);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> stringSetting.get(settings));
assertEquals("Failed to parse [[bla-a, bla-b]] for string setting [foo.bar] because it is not scalar.", e.getMessage());
}

private static final Setting<String> FOO_BAR_SETTING = new Setting<>(
"foo.bar",
"foobar",
Expand Down