org.elasticsearch.common.settings.Setting Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of elasticsearch Show documentation
Show all versions of elasticsearch Show documentation
Elasticsearch subproject :server
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.settings;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.VersionId;
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.MemorySizeValue;
import org.elasticsearch.common.xcontent.XContentParserUtils;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.XContentParserConfiguration;
import org.elasticsearch.xcontent.XContentType;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A setting. Encapsulates typical stuff like default value, parsing, and scope.
* Some (SettingsProperty.Dynamic) can by modified at run time using the API.
* All settings inside elasticsearch or in any of the plugins should use this type-safe and generic settings infrastructure
* together with {@link AbstractScopedSettings}. This class contains several utility methods that makes it straight forward
* to add settings for the majority of the cases. For instance a simple boolean settings can be defined like this:
* {@code
* public static final Setting; MY_BOOLEAN = Setting.boolSetting("my.bool.setting", true, SettingsProperty.NodeScope);}
*
* To retrieve the value of the setting a {@link Settings} object can be passed directly to the {@link Setting#get(Settings)} method.
*
* final boolean myBooleanValue = MY_BOOLEAN.get(settings);
*
* It's recommended to use typed settings rather than string based settings. For example adding a setting for an enum type:
* {@code
* public enum Color {
* RED, GREEN, BLUE;
* }
* public static final Setting MY_BOOLEAN =
* new Setting<>("my.color.setting", Color.RED.toString(), Color::valueOf, SettingsProperty.NodeScope);
* }
*
*/
public class Setting implements ToXContentObject {
public enum Property {
/**
* should be filtered in some api (mask password/credentials)
*/
Filtered,
/**
* iff this setting can be dynamically updateable
*/
Dynamic,
/**
* Operator only Dynamic setting
*/
OperatorDynamic,
/**
* mark this setting as final, not updateable even when the context is not dynamic
* ie. Setting this property on an index scoped setting will fail update when the index is closed
*/
Final,
/**
* mark this setting as deprecated (critical level)
*/
Deprecated,
/**
* mark this setting as deprecated (warning level)
*/
DeprecatedWarning,
/**
* Node scope
*/
NodeScope,
/**
* Secure setting values equal on all nodes
*/
Consistent,
/**
* Index scope
*/
IndexScope,
/**
* Mark this setting as not copyable during an index resize (shrink or split). This property can only be applied to settings that
* also have {@link Property#IndexScope}.
*/
NotCopyableOnResize,
/**
* Indicates an index-level setting that is managed internally. Such a setting can only be added to an index on index creation but
* can not be updated via the update API.
*/
InternalIndex,
/**
* Indicates an index-level setting that is privately managed. Such a setting can not even be set on index creation.
*/
PrivateIndex,
/**
* Indicates that this index-level setting was deprecated in {@link Version#V_7_17_0} and is
* forbidden in indices created from {@link Version#V_8_0_0} onwards.
*/
IndexSettingDeprecatedInV7AndRemovedInV8,
/**
* Indicates that this setting is accessible by non-operator users (public) in serverless
* Users will be allowed to set and see values of this setting.
* All other settings will be rejected when used on a PUT request
* and filtered out on a GET
*/
ServerlessPublic
}
private final Key key;
protected final Function defaultValue;
@Nullable
private final Setting fallbackSetting;
private final Function parser;
private final Validator validator;
private final EnumSet properties;
private static final EnumSet EMPTY_PROPERTIES = EnumSet.noneOf(Property.class);
private static final EnumSet DEPRECATED_PROPERTIES = EnumSet.of(
Property.Deprecated,
Property.DeprecatedWarning,
Property.IndexSettingDeprecatedInV7AndRemovedInV8
);
@SuppressWarnings("this-escape")
private Setting(
Key key,
@Nullable Setting fallbackSetting,
Function defaultValue,
Function parser,
Validator validator,
Property... properties
) {
assert this instanceof SecureSetting || this.isGroupSetting() || parser.apply(defaultValue.apply(Settings.EMPTY)) != null
: "parser returned null";
this.key = key;
this.fallbackSetting = fallbackSetting;
this.defaultValue = defaultValue;
this.parser = parser;
this.validator = validator;
if (properties == null) {
throw new IllegalArgumentException("properties cannot be null for setting [" + key + "]");
}
if (properties.length == 0) {
this.properties = EMPTY_PROPERTIES;
} else {
final EnumSet propertiesAsSet = EnumSet.copyOf(Arrays.asList(properties));
if ((propertiesAsSet.contains(Property.Dynamic) || propertiesAsSet.contains(Property.OperatorDynamic))
&& propertiesAsSet.contains(Property.Final)) {
throw new IllegalArgumentException("final setting [" + key + "] cannot be dynamic");
}
if (propertiesAsSet.contains(Property.Dynamic) && propertiesAsSet.contains(Property.OperatorDynamic)) {
throw new IllegalArgumentException("setting [" + key + "] cannot be both dynamic and operator dynamic");
}
if (propertiesAsSet.stream().filter(DEPRECATED_PROPERTIES::contains).count() > 1) {
throw new IllegalArgumentException("setting [" + key + "] must be at most one of [" + DEPRECATED_PROPERTIES + "]");
}
checkPropertyRequiresIndexScope(propertiesAsSet, Property.NotCopyableOnResize);
checkPropertyRequiresIndexScope(propertiesAsSet, Property.InternalIndex);
checkPropertyRequiresIndexScope(propertiesAsSet, Property.PrivateIndex);
checkPropertyRequiresIndexScope(propertiesAsSet, Property.IndexSettingDeprecatedInV7AndRemovedInV8);
checkPropertyRequiresNodeScope(propertiesAsSet);
this.properties = propertiesAsSet;
}
}
private void checkPropertyRequiresIndexScope(final EnumSet properties, final Property property) {
if (properties.contains(property) && properties.contains(Property.IndexScope) == false) {
throw new IllegalArgumentException("non-index-scoped setting [" + key + "] can not have property [" + property + "]");
}
}
private void checkPropertyRequiresNodeScope(final EnumSet properties) {
if (properties.contains(Property.Consistent) && properties.contains(Property.NodeScope) == false) {
throw new IllegalArgumentException("non-node-scoped setting [" + key + "] can not have property [" + Property.Consistent + "]");
}
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(Key key, Function defaultValue, Function parser, Property... properties) {
this(key, defaultValue, parser, v -> {}, properties);
}
/**
* Creates a new {@code Setting} instance.
*
* @param key the settings key for this setting
* @param defaultValue a default value function that results a string representation of the default value
* @param parser a parser that parses a string representation into the concrete type for this setting
* @param validator a {@link Validator} for validating this setting
* @param properties properties for this setting
*/
@SuppressWarnings("this-escape")
public Setting(
Key key,
Function defaultValue,
Function parser,
Validator validator,
Property... properties
) {
this(key, null, defaultValue, parser, validator, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, String defaultValue, Function parser, Property... properties) {
this(key, s -> defaultValue, parser, properties);
}
/**
* Creates a new {@code Setting} instance.
*
* @param key the settings key for this setting
* @param defaultValue a default value function that results a string representation of the default value
* @param parser a parser that parses a string representation into the concrete type for this setting
* @param validator a {@link Validator} for validating this setting
* @param properties properties for this setting
*/
public Setting(String key, String defaultValue, Function parser, Validator validator, Property... properties) {
this(new SimpleKey(key), s -> defaultValue, parser, validator, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Function defaultValue, Function parser, Property... properties) {
this(new SimpleKey(key), defaultValue, parser, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param validator a {@link Validator} for validating this setting
* @param properties properties for this setting like scope, filtering...
*/
public Setting(
String key,
Function defaultValue,
Function parser,
Validator validator,
Property... properties
) {
this(new SimpleKey(key), defaultValue, parser, validator, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallbackSetting a setting who's value to fallback on if this setting is not defined
* @param parser a parser that parses the string rep into a complex datatype.
* @param validator a {@link Validator} for validating this setting
* @param properties properties for this setting like scope, filtering...
*/
@SuppressWarnings("this-escape")
public Setting(String key, Setting fallbackSetting, Function parser, Validator validator, Property... properties) {
this(new SimpleKey(key), fallbackSetting, fallbackSetting::getRaw, parser, validator, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallbackSetting a setting who's value to fallback on if this setting is not defined
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
@SuppressWarnings("this-escape")
public Setting(Key key, Setting fallbackSetting, Function parser, Property... properties) {
this(key, fallbackSetting, fallbackSetting::getRaw, parser, v -> {}, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallBackSetting a setting to fall back to if the current setting is not set.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Setting fallBackSetting, Function parser, Property... properties) {
this(new SimpleKey(key), fallBackSetting, parser, properties);
}
/**
* Returns the settings key or a prefix if this setting is a group setting.
* Note: this method should not be used to retrieve a value from a {@link Settings} object.
* Use {@link #get(Settings)} instead
*
* @see #isGroupSetting()
*/
public final String getKey() {
return key.toString();
}
/**
* Returns the original representation of a setting key.
*/
public final Key getRawKey() {
return key;
}
/**
* Returns true
if this setting is dynamically updateable, otherwise false
*/
public final boolean isDynamic() {
return properties.contains(Property.Dynamic) || properties.contains(Property.OperatorDynamic);
}
/**
* Returns true
if this setting is dynamically updateable by operators, otherwise false
*/
public final boolean isOperatorOnly() {
return properties.contains(Property.OperatorDynamic);
}
/**
* Returns true
if this setting is accessibly by non-operators (public users), otherwise false
*/
public final boolean isServerlessPublic() {
return properties.contains(Property.ServerlessPublic);
}
/**
* Returns true
if this setting is final, otherwise false
*/
public final boolean isFinal() {
return properties.contains(Property.Final);
}
public final boolean isInternalIndex() {
return properties.contains(Property.InternalIndex);
}
public final boolean isPrivateIndex() {
return properties.contains(Property.PrivateIndex);
}
/**
* Returns the setting properties
* @see Property
*/
public EnumSet getProperties() {
return properties;
}
/**
* Returns true
if this setting must be filtered, otherwise false
*/
public boolean isFiltered() {
return properties.contains(Property.Filtered);
}
/**
* Returns true
if this setting has a node scope, otherwise false
*/
public boolean hasNodeScope() {
return properties.contains(Property.NodeScope);
}
/**
* Returns true
if this setting's value can be checked for equality across all nodes. Only {@link SecureSetting} instances
* may have this qualifier.
*/
public boolean isConsistent() {
return properties.contains(Property.Consistent);
}
/**
* Returns true
if this setting has an index scope, otherwise false
*/
public boolean hasIndexScope() {
return properties.contains(Property.IndexScope);
}
/**
* Returns true
if this setting is deprecated, otherwise false
*/
private boolean isDeprecated() {
return properties.contains(Property.Deprecated)
|| properties.contains(Property.DeprecatedWarning)
|| properties.contains(Property.IndexSettingDeprecatedInV7AndRemovedInV8);
}
private boolean isDeprecatedWarningOnly() {
return properties.contains(Property.DeprecatedWarning);
}
public boolean isDeprecatedAndRemoved() {
return properties.contains(Property.IndexSettingDeprecatedInV7AndRemovedInV8);
}
/**
* Returns true
iff this setting is a group setting. Group settings represent a set of settings rather than a single value.
* The key, see {@link #getKey()}, in contrast to non-group settings is a prefix like {@code cluster.store.} that matches all settings
* with this prefix.
*/
boolean isGroupSetting() {
return false;
}
final boolean isListSetting() {
return this instanceof ListSetting;
}
boolean hasComplexMatcher() {
return isGroupSetting();
}
/**
* Validate the current setting value only without dependencies with {@link Setting.Validator#validate(Object)}.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
void validateWithoutDependencies(Settings settings) {
validator.validate(get(settings, false));
}
/**
* Returns the default value string representation for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public String getDefaultRaw(Settings settings) {
return defaultValue.apply(settings);
}
/**
* Returns the default value for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public T getDefault(Settings settings) {
return parser.apply(getDefaultRaw(settings));
}
/**
* Returns true if and only if this setting is present in the given settings instance. Note that fallback settings are excluded.
*
* @param settings the settings
* @return true if the setting is present in the given settings instance, otherwise false
*/
public boolean exists(final Settings settings) {
return exists(settings.keySet(), settings.getSecureSettings());
}
public boolean exists(final Settings.Builder builder) {
return exists(builder.keys(), builder.getSecureSettings());
}
private boolean exists(final Set keys, final SecureSettings secureSettings) {
final String key = getKey();
return keys.contains(key) && (secureSettings == null || secureSettings.getSettingNames().contains(key) == false);
}
/**
* Returns true if and only if this setting including fallback settings is present in the given settings instance.
*
* @param settings the settings
* @return true if the setting including fallback settings is present in the given settings instance, otherwise false
*/
public boolean existsOrFallbackExists(final Settings settings) {
return settings.keySet().contains(getKey()) || (fallbackSetting != null && fallbackSetting.existsOrFallbackExists(settings));
}
/**
* Returns the settings value. If the setting is not present in the given settings object the default value is returned
* instead.
*/
public T get(Settings settings) {
return get(settings, true);
}
private T get(Settings settings, boolean validate) {
String value = getRaw(settings);
try {
T parsed = parser.apply(value);
if (validate) {
final Iterator> it = validator.settings();
final Map, Object> map;
if (it.hasNext()) {
map = new HashMap<>();
while (it.hasNext()) {
final Setting setting = it.next();
if (setting instanceof AffixSetting as) {
// Collect all possible concrete settings
for (String ns : as.getNamespaces(settings)) {
Setting s = as.getConcreteSettingForNamespace(ns);
map.put(s, s.get(settings, false));
}
} else {
map.put(setting, setting.get(settings, false)); // we have to disable validation or we will stack overflow
}
}
} else {
map = Collections.emptyMap();
}
validator.validate(parsed);
validator.validate(parsed, map);
validator.validate(parsed, map, exists(settings));
}
return parsed;
} catch (ElasticsearchParseException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
} catch (NumberFormatException ex) {
String err = "Failed to parse value" + (isFiltered() ? "" : " [" + value + "]") + " for setting [" + getKey() + "]";
throw new IllegalArgumentException(err, ex);
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception t) {
String err = "Failed to parse value" + (isFiltered() ? "" : " [" + value + "]") + " for setting [" + getKey() + "]";
throw new IllegalArgumentException(err, t);
}
}
/**
* Add this setting to the builder if it doesn't exists in the source settings.
* The value added to the builder is taken from the given default settings object.
* @param builder the settings builder to fill the diff into
* @param source the source settings object to diff
* @param defaultSettings the default settings object to diff against
*/
public void diff(Settings.Builder builder, Settings source, Settings defaultSettings) {
if (exists(source) == false) {
if (exists(defaultSettings)) {
// If the setting is only in the defaults, use the value from the defaults
builder.put(getKey(), getRaw(defaultSettings));
} else {
// If the setting is in neither `source` nor `default`, get the value
// from `source` as it may depend on the value of other settings
builder.put(getKey(), getRaw(source));
}
}
}
/**
* Returns the raw (string) settings value. If the setting is not present in the given settings object the default value is returned
* instead. This is useful if the value can't be parsed due to an invalid value to access the actual value.
*/
private String getRaw(final Settings settings) {
checkDeprecation(settings);
return innerGetRaw(settings);
}
/**
* The underlying implementation for {@link #getRaw(Settings)}. Setting specializations can override this as needed to convert the
* actual settings value to raw strings.
*
* @param settings the settings instance
* @return the raw string representation of the setting value
*/
String innerGetRaw(final Settings settings) {
final String key = getKey();
SecureSettings secureSettings = settings.getSecureSettings();
if (secureSettings != null && secureSettings.getSettingNames().contains(key)) {
throw new IllegalArgumentException(
"Setting ["
+ key
+ "] is a non-secure setting"
+ " and must be stored inside elasticsearch.yml, but was found inside the Elasticsearch keystore"
);
}
final String found = settings.get(key);
if (found != null) {
return found;
}
return defaultValue.apply(settings);
}
/** Logs a deprecation warning if the setting is deprecated and used. */
void checkDeprecation(Settings settings) {
// They're using the setting, so we need to tell them to stop
if (this.isDeprecated() && this.exists(settings)) {
// It would be convenient to show its replacement key, but replacement is often not so simple
final String key = getKey();
String message = "[{}] setting was deprecated in Elasticsearch and will be removed in a future release.";
if (this.isDeprecatedWarningOnly()) {
Settings.DeprecationLoggerHolder.deprecationLogger.warn(DeprecationCategory.SETTINGS, key, message, key);
} else if (this.isDeprecatedAndRemoved()) {
Settings.DeprecationLoggerHolder.deprecationLogger.critical(
DeprecationCategory.SETTINGS,
key,
"[{}] setting was deprecated in the previous Elasticsearch release and is removed in this release.",
key
);
} else {
Settings.DeprecationLoggerHolder.deprecationLogger.critical(DeprecationCategory.SETTINGS, key, message, key);
}
}
}
/**
* Returns true
iff the given key matches the settings key or if this setting is a group setting if the
* given key is part of the settings group.
* @see #isGroupSetting()
*/
public final boolean match(String toTest) {
return key.match(toTest);
}
@Override
public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("key", getKey());
builder.enumSet("properties", properties);
builder.field("is_group_setting", isGroupSetting());
builder.field("default", defaultValue.apply(Settings.EMPTY));
builder.endObject();
return builder;
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
/**
* Returns the value for this setting but falls back to the second provided settings object
*/
public final T get(Settings primary, Settings secondary) {
if (exists(primary)) {
return get(primary);
}
if (exists(secondary)) {
return get(secondary);
}
if (fallbackSetting == null) {
return get(primary);
}
if (fallbackSetting.exists(primary)) {
return fallbackSetting.get(primary);
}
return fallbackSetting.get(secondary);
}
public Setting getConcreteSetting(String key) {
// we use startsWith here since the key might be foo.bar.0 if it's an array
assert key.startsWith(this.getKey()) : "was " + key + " expected: " + getKey();
return this;
}
/**
* Allows a setting to declare a dependency on another setting being set. Optionally, a setting can validate the value of the dependent
* setting.
*/
public interface SettingDependency {
/**
* The setting to declare a dependency on.
*
* @return the setting
*/
Setting getSetting();
/**
* Validates the dependent setting value.
*
* @param key the key for this setting
* @param value the value of this setting
* @param dependency the value of the dependent setting
*/
default void validate(String key, Object value, Object dependency) {
}
}
/**
* Returns a set of settings that are required at validation time. Unless all of the dependencies are present in the settings
* object validation of setting must fail.
*/
public Set getSettingsDependencies(final String key) {
return Collections.emptySet();
}
/**
* Build a new updater with a noop validator.
*/
final AbstractScopedSettings.SettingUpdater newUpdater(Consumer consumer, Logger logger) {
return newUpdater(consumer, logger, (s) -> {});
}
/**
* Build the updater responsible for validating new values, logging the new
* value, and eventually setting the value where it belongs.
*/
AbstractScopedSettings.SettingUpdater newUpdater(Consumer consumer, Logger logger, Consumer validator) {
if (isDynamic()) {
return new Updater(consumer, logger, validator);
} else {
throw new IllegalStateException("setting [" + getKey() + "] is not dynamic");
}
}
/**
* Updates settings that depend on each other.
* See {@link AbstractScopedSettings#addSettingsUpdateConsumer(Setting, Setting, BiConsumer)} and its usage for details.
*/
static AbstractScopedSettings.SettingUpdater> compoundUpdater(
final BiConsumer consumer,
final BiConsumer validator,
final Setting aSetting,
final Setting bSetting,
Logger logger
) {
final AbstractScopedSettings.SettingUpdater aSettingUpdater = aSetting.newUpdater(null, logger);
final AbstractScopedSettings.SettingUpdater bSettingUpdater = bSetting.newUpdater(null, logger);
return new AbstractScopedSettings.SettingUpdater<>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return aSettingUpdater.hasChanged(current, previous) || bSettingUpdater.hasChanged(current, previous);
}
@Override
public Tuple getValue(Settings current, Settings previous) {
A valueA = aSettingUpdater.getValue(current, previous);
B valueB = bSettingUpdater.getValue(current, previous);
validator.accept(valueA, valueB);
return new Tuple<>(valueA, valueB);
}
@Override
public void apply(Tuple value, Settings current, Settings previous) {
if (aSettingUpdater.hasChanged(current, previous)) {
logSettingUpdate(aSetting, current, previous, logger);
}
if (bSettingUpdater.hasChanged(current, previous)) {
logSettingUpdate(bSetting, current, previous, logger);
}
consumer.accept(value.v1(), value.v2());
}
@Override
public String toString() {
return "CompoundUpdater for: " + aSettingUpdater + " and " + bSettingUpdater;
}
};
}
static AbstractScopedSettings.SettingUpdater groupedSettingsUpdater(
Consumer consumer,
final List> configuredSettings
) {
return groupedSettingsUpdater(consumer, configuredSettings, (v) -> {});
}
static AbstractScopedSettings.SettingUpdater groupedSettingsUpdater(
Consumer consumer,
final List> configuredSettings,
Consumer validator
) {
return new AbstractScopedSettings.SettingUpdater<>() {
private Settings get(Settings settings) {
return settings.filter(s -> {
for (Setting setting : configuredSettings) {
if (setting.key.match(s)) {
return true;
}
}
return false;
});
}
@Override
public boolean hasChanged(Settings current, Settings previous) {
Settings currentSettings = get(current);
Settings previousSettings = get(previous);
return currentSettings.equals(previousSettings) == false;
}
@Override
public Settings getValue(Settings current, Settings previous) {
validator.accept(current);
return get(current);
}
@Override
public void apply(Settings value, Settings current, Settings previous) {
consumer.accept(value);
}
@Override
public String toString() {
return "Updater grouped: " + configuredSettings.stream().map(Setting::getKey).collect(Collectors.joining(", "));
}
};
}
/**
* Allows an affix setting to declare a dependency on another affix setting.
*/
public interface AffixSettingDependency extends SettingDependency {
@Override
AffixSetting getSetting();
}
public static class AffixSetting extends Setting {
private final AffixKey key;
private final BiFunction> delegateFactory;
private final Set dependencies;
public AffixSetting(
AffixKey key,
Setting delegate,
BiFunction> delegateFactory,
AffixSettingDependency... dependencies
) {
super(key, delegate.defaultValue, delegate.parser, delegate.properties.toArray(new Property[0]));
this.key = key;
this.delegateFactory = delegateFactory;
this.dependencies = Set.of(dependencies);
}
boolean isGroupSetting() {
return true;
}
private Stream matchStream(Settings settings) {
return settings.keySet().stream().filter(this::match).map(key::getConcreteString);
}
/**
* Get the raw list of dependencies. This method is exposed for testing purposes and {@link #getSettingsDependencies(String)}
* should be preferred for most all cases.
* @return the raw list of dependencies for this setting
*/
public Set getDependencies() {
return dependencies;
}
@Override
public Set getSettingsDependencies(String settingsKey) {
if (dependencies.isEmpty()) {
return Collections.emptySet();
} else {
String namespace = key.getNamespace(settingsKey);
return dependencies.stream().map(s -> new SettingDependency() {
@Override
public Setting getSetting() {
return s.getSetting().getConcreteSettingForNamespace(namespace);
}
@Override
public void validate(final String key, final Object value, final Object dependency) {
s.validate(key, value, dependency);
}
}).collect(Collectors.toSet());
}
}
AbstractScopedSettings.SettingUpdater