-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Settings.java
1444 lines (1312 loc) · 55.6 KB
/
Settings.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.settings;
import org.apache.logging.log4j.Level;
import org.opensearch.OpenSearchGenerationException;
import org.opensearch.OpenSearchParseException;
import org.opensearch.Version;
import org.opensearch.common.Booleans;
import org.opensearch.common.SetOnce;
import org.opensearch.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.common.logging.DeprecationLogger;
import org.opensearch.common.logging.LogConfigurator;
import org.opensearch.common.unit.ByteSizeUnit;
import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.MemorySizeValue;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.xcontent.XContentParserUtils;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.common.settings.SecureString;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.MediaType;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.util.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.opensearch.common.unit.ByteSizeValue.parseBytesSizeValue;
import static org.opensearch.common.unit.TimeValue.parseTimeValue;
/**
* An immutable settings implementation.
*
* @opensearch.internal
*/
public final class Settings implements ToXContentFragment {
public static final Settings EMPTY = new Builder().build();
/** The raw settings from the full key to raw string value. */
private final Map<String, Object> settings;
/** The secure settings storage associated with these settings. */
private final SecureSettings secureSettings;
/** The first level of setting names. This is constructed lazily in {@link #names()}. */
private final SetOnce<Set<String>> firstLevelNames = new SetOnce<>();
/**
* Setting names found in this Settings for both string and secure settings.
* This is constructed lazily in {@link #keySet()}.
*/
private final SetOnce<Set<String>> keys = new SetOnce<>();
private Settings(Map<String, Object> settings, SecureSettings secureSettings) {
// we use a sorted map for consistent serialization when using getAsMap()
this.settings = Collections.unmodifiableSortedMap(new TreeMap<>(settings));
this.secureSettings = secureSettings;
}
/**
* Retrieve the secure settings in these settings.
*/
SecureSettings getSecureSettings() {
// pkg private so it can only be accessed by local subclasses of SecureSetting
return secureSettings;
}
private Map<String, Object> getAsStructuredMap() {
Map<String, Object> map = new HashMap<>(2);
for (Map.Entry<String, Object> entry : settings.entrySet()) {
processSetting(map, "", entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> valMap = (Map<String, Object>) entry.getValue();
entry.setValue(convertMapsToArrays(valMap));
}
}
return map;
}
private void processSetting(Map<String, Object> map, String prefix, String setting, Object value) {
int prefixLength = setting.indexOf('.');
if (prefixLength == -1) {
@SuppressWarnings("unchecked")
Map<String, Object> innerMap = (Map<String, Object>) map.get(prefix + setting);
if (innerMap != null) {
// It supposed to be a value, but we already have a map stored, need to convert this map to "." notation
for (Map.Entry<String, Object> entry : innerMap.entrySet()) {
map.put(prefix + setting + "." + entry.getKey(), entry.getValue());
}
}
map.put(prefix + setting, value);
} else {
String key = setting.substring(0, prefixLength);
String rest = setting.substring(prefixLength + 1);
Object existingValue = map.get(prefix + key);
if (existingValue == null) {
Map<String, Object> newMap = new HashMap<>(2);
processSetting(newMap, "", rest, value);
map.put(prefix + key, newMap);
} else {
if (existingValue instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> innerMap = (Map<String, Object>) existingValue;
processSetting(innerMap, "", rest, value);
map.put(prefix + key, innerMap);
} else {
// It supposed to be a map, but we already have a value stored, which is not a map
// fall back to "." notation
processSetting(map, prefix + key + ".", rest, value);
}
}
}
}
private Object convertMapsToArrays(Map<String, Object> map) {
if (map.isEmpty()) {
return map;
}
boolean isArray = true;
int maxIndex = -1;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (isArray) {
try {
int index = Integer.parseInt(entry.getKey());
if (index >= 0) {
maxIndex = Math.max(maxIndex, index);
} else {
isArray = false;
}
} catch (NumberFormatException ex) {
isArray = false;
}
}
if (entry.getValue() instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> valMap = (Map<String, Object>) entry.getValue();
entry.setValue(convertMapsToArrays(valMap));
}
}
if (isArray && (maxIndex + 1) == map.size()) {
ArrayList<Object> newValue = new ArrayList<>(maxIndex + 1);
for (int i = 0; i <= maxIndex; i++) {
Object obj = map.get(Integer.toString(i));
if (obj == null) {
// Something went wrong. Different format?
// Bailout!
return map;
}
newValue.add(obj);
}
return newValue;
}
return map;
}
/**
* A settings that are filtered (and key is removed) with the specified prefix.
*/
public Settings getByPrefix(String prefix) {
return new Settings(
new FilteredMap(this.settings, (k) -> k.startsWith(prefix), prefix),
secureSettings == null ? null : new PrefixedSecureSettings(secureSettings, prefix, s -> s.startsWith(prefix))
);
}
/**
* Returns a new settings object that contains all setting of the current one filtered by the given settings key predicate.
*/
public Settings filter(Predicate<String> predicate) {
return new Settings(
new FilteredMap(this.settings, predicate, null),
secureSettings == null ? null : new PrefixedSecureSettings(secureSettings, "", predicate)
);
}
/**
* Returns the settings mapped to the given setting name.
*/
public Settings getAsSettings(String setting) {
return getByPrefix(setting + ".");
}
/**
* Returns the setting value associated with the setting key.
*
* @param setting The setting key
* @return The setting value, {@code null} if it does not exists.
*/
public String get(String setting) {
return toString(settings.get(setting));
}
/**
* Returns the setting value associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public String get(String setting, String defaultValue) {
String retVal = get(setting);
return retVal == null ? defaultValue : retVal;
}
/**
* Returns the setting value (as float) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public Float getAsFloat(String setting, Float defaultValue) {
String sValue = get(setting);
if (sValue == null) {
return defaultValue;
}
try {
return Float.parseFloat(sValue);
} catch (NumberFormatException e) {
throw new SettingsException("Failed to parse float setting [" + setting + "] with value [" + sValue + "]", e);
}
}
/**
* Returns the setting value (as double) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public Double getAsDouble(String setting, Double defaultValue) {
String sValue = get(setting);
if (sValue == null) {
return defaultValue;
}
try {
return Double.parseDouble(sValue);
} catch (NumberFormatException e) {
throw new SettingsException("Failed to parse double setting [" + setting + "] with value [" + sValue + "]", e);
}
}
/**
* Returns the setting value (as int) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public Integer getAsInt(String setting, Integer defaultValue) {
String sValue = get(setting);
if (sValue == null) {
return defaultValue;
}
try {
return Integer.parseInt(sValue);
} catch (NumberFormatException e) {
throw new SettingsException("Failed to parse int setting [" + setting + "] with value [" + sValue + "]", e);
}
}
/**
* Returns the setting value (as long) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public Long getAsLong(String setting, Long defaultValue) {
String sValue = get(setting);
if (sValue == null) {
return defaultValue;
}
try {
return Long.parseLong(sValue);
} catch (NumberFormatException e) {
throw new SettingsException("Failed to parse long setting [" + setting + "] with value [" + sValue + "]", e);
}
}
/**
* Returns <code>true</code> iff the given key has a value in this settings object
*/
public boolean hasValue(String key) {
return settings.get(key) != null;
}
/**
* We have to lazy initialize the deprecation logger as otherwise a static logger here would be constructed before logging is configured
* leading to a runtime failure (see {@link LogConfigurator#checkErrorListener()} ). The premature construction would come from any
* {@link Setting} object constructed in, for example, {@link org.opensearch.env.Environment}.
*
* @opensearch.internal
*/
static class DeprecationLoggerHolder {
static DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(Settings.class);
}
/**
* Returns the setting value (as boolean) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public Boolean getAsBoolean(String setting, Boolean defaultValue) {
return Booleans.parseBoolean(get(setting), defaultValue);
}
/**
* Returns the setting value (as time) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public TimeValue getAsTime(String setting, TimeValue defaultValue) {
return parseTimeValue(get(setting), defaultValue, setting);
}
/**
* Returns the setting value (as size) associated with the setting key. If it does not exists,
* returns the default value provided.
*/
public ByteSizeValue getAsBytesSize(String setting, ByteSizeValue defaultValue) throws SettingsException {
return parseBytesSizeValue(get(setting), defaultValue, setting);
}
/**
* Returns the setting value (as size) associated with the setting key. Provided values can either be
* absolute values (interpreted as a number of bytes), byte sizes (eg. 1mb) or percentage of the heap size
* (eg. 12%). If it does not exists, parses the default value provided.
*/
public ByteSizeValue getAsMemory(String setting, String defaultValue) throws SettingsException {
return MemorySizeValue.parseBytesSizeValueOrHeapRatio(get(setting, defaultValue), setting);
}
/**
* The values associated with a setting key as an immutable list.
* <p>
* It will also automatically load a comma separated list under the settingPrefix and merge with
* the numbered format.
*
* @param key The setting key to load the list by
* @return The setting list values
*/
public List<String> getAsList(String key) throws SettingsException {
return getAsList(key, Collections.emptyList());
}
/**
* The values associated with a setting key as an immutable list.
* <p>
* If commaDelimited is true, it will automatically load a comma separated list under the settingPrefix and merge with
* the numbered format.
*
* @param key The setting key to load the list by
* @return The setting list values
*/
public List<String> getAsList(String key, List<String> defaultValue) throws SettingsException {
return getAsList(key, defaultValue, true);
}
/**
* The values associated with a setting key as an immutable list.
* <p>
* It will also automatically load a comma separated list under the settingPrefix and merge with
* the numbered format.
*
* @param key The setting key to load the list by
* @param defaultValue The default value to use if no value is specified
* @param commaDelimited Whether to try to parse a string as a comma-delimited value
* @return The setting list values
*/
public List<String> getAsList(String key, List<String> defaultValue, Boolean commaDelimited) throws SettingsException {
List<String> result = new ArrayList<>();
final Object valueFromPrefix = settings.get(key);
if (valueFromPrefix != null) {
if (valueFromPrefix instanceof List) {
return Collections.unmodifiableList((List<String>) valueFromPrefix);
} else if (commaDelimited) {
String[] strings = org.opensearch.core.common.Strings.splitStringByCommaToArray(get(key));
if (strings.length > 0) {
for (String string : strings) {
result.add(string.trim());
}
}
} else {
result.add(get(key).trim());
}
}
if (result.isEmpty()) {
return defaultValue;
}
return Collections.unmodifiableList(result);
}
/**
* Returns group settings for the given setting prefix.
*/
public Map<String, Settings> getGroups(String settingPrefix) throws SettingsException {
return getGroups(settingPrefix, false);
}
/**
* Returns group settings for the given setting prefix.
*/
public Map<String, Settings> getGroups(String settingPrefix, boolean ignoreNonGrouped) throws SettingsException {
if (!org.opensearch.core.common.Strings.hasLength(settingPrefix)) {
throw new IllegalArgumentException("illegal setting prefix " + settingPrefix);
}
if (settingPrefix.charAt(settingPrefix.length() - 1) != '.') {
settingPrefix = settingPrefix + ".";
}
return getGroupsInternal(settingPrefix, ignoreNonGrouped);
}
private Map<String, Settings> getGroupsInternal(String settingPrefix, boolean ignoreNonGrouped) throws SettingsException {
Settings prefixSettings = getByPrefix(settingPrefix);
Map<String, Settings> groups = new HashMap<>();
for (String groupName : prefixSettings.names()) {
Settings groupSettings = prefixSettings.getByPrefix(groupName + ".");
if (groupSettings.isEmpty()) {
if (ignoreNonGrouped) {
continue;
}
throw new SettingsException(
"Failed to get setting group for ["
+ settingPrefix
+ "] setting prefix and setting ["
+ settingPrefix
+ groupName
+ "] because of a missing '.'"
);
}
groups.put(groupName, groupSettings);
}
return Collections.unmodifiableMap(groups);
}
/**
* Returns group settings for the given setting prefix.
*/
public Map<String, Settings> getAsGroups() throws SettingsException {
return getGroupsInternal("", false);
}
/**
* Returns a parsed version.
*/
public Version getAsVersion(String setting, Version defaultVersion) throws SettingsException {
String sValue = get(setting);
if (sValue == null) {
return defaultVersion;
}
try {
return Version.fromId(Integer.parseInt(sValue));
} catch (Exception e) {
throw new SettingsException("Failed to parse version setting [" + setting + "] with value [" + sValue + "]", e);
}
}
/**
* @return The direct keys of this settings
*/
public Set<String> names() {
synchronized (firstLevelNames) {
if (firstLevelNames.get() == null) {
Stream<String> stream = settings.keySet().stream();
if (secureSettings != null) {
stream = Stream.concat(stream, secureSettings.getSettingNames().stream());
}
Set<String> names = stream.map(k -> {
int i = k.indexOf('.');
if (i < 0) {
return k;
} else {
return k.substring(0, i);
}
}).collect(Collectors.toSet());
firstLevelNames.set(Collections.unmodifiableSet(names));
}
}
return firstLevelNames.get();
}
/**
* Returns the settings as delimited string.
*/
public String toDelimitedString(char delimiter) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> entry : settings.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append(delimiter);
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Settings that = (Settings) o;
return Objects.equals(settings, that.settings);
}
@Override
public int hashCode() {
return settings != null ? settings.hashCode() : 0;
}
public static Settings readSettingsFromStream(StreamInput in) throws IOException {
Builder builder = new Builder();
int numberOfSettings = in.readVInt();
for (int i = 0; i < numberOfSettings; i++) {
String key = in.readString();
Object value = in.readGenericValue();
if (value == null) {
builder.putNull(key);
} else if (value instanceof List) {
builder.putList(key, (List<String>) value);
} else {
builder.put(key, value.toString());
}
}
return builder.build();
}
public static void writeSettingsToStream(Settings settings, StreamOutput out) throws IOException {
// pull settings to exclude secure settings in size()
Set<Map.Entry<String, Object>> entries = settings.settings.entrySet();
out.writeVInt(entries.size());
for (Map.Entry<String, Object> entry : entries) {
out.writeString(entry.getKey());
out.writeGenericValue(entry.getValue());
}
}
/**
* Returns a builder to be used in order to build settings.
*/
public static Builder builder() {
return new Builder();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
Settings settings = SettingsFilter.filterSettings(params, this);
if (!params.paramAsBoolean("flat_settings", false)) {
for (Map.Entry<String, Object> entry : settings.getAsStructuredMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
} else {
for (Map.Entry<String, Object> entry : settings.settings.entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
}
return builder;
}
/**
* Parsers the generated xcontent from {@link Settings#toXContent(XContentBuilder, Params)} into a new Settings object.
* Note this method requires the parser to either be positioned on a null token or on
* {@link XContentParser.Token#START_OBJECT}.
*/
public static Settings fromXContent(XContentParser parser) throws IOException {
return fromXContent(parser, true, false);
}
private static Settings fromXContent(XContentParser parser, boolean allowNullValues, boolean validateEndOfStream) throws IOException {
if (parser.currentToken() == null) {
parser.nextToken();
}
XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
Builder innerBuilder = Settings.builder();
StringBuilder currentKeyBuilder = new StringBuilder();
fromXContent(parser, currentKeyBuilder, innerBuilder, allowNullValues);
if (validateEndOfStream) {
// ensure we reached the end of the stream
XContentParser.Token lastToken = null;
try {
while (!parser.isClosed() && (lastToken = parser.nextToken()) == null)
;
} catch (Exception e) {
throw new OpenSearchParseException(
"malformed, expected end of settings but encountered additional content starting at line number: [{}], "
+ "column number: [{}]",
e,
parser.getTokenLocation().lineNumber,
parser.getTokenLocation().columnNumber
);
}
if (lastToken != null) {
throw new OpenSearchParseException(
"malformed, expected end of settings but encountered additional content starting at line number: [{}], "
+ "column number: [{}]",
parser.getTokenLocation().lineNumber,
parser.getTokenLocation().columnNumber
);
}
}
return innerBuilder.build();
}
private static void fromXContent(XContentParser parser, StringBuilder keyBuilder, Settings.Builder builder, boolean allowNullValues)
throws IOException {
final int length = keyBuilder.length();
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
if (parser.currentToken() == XContentParser.Token.FIELD_NAME) {
keyBuilder.setLength(length);
keyBuilder.append(parser.currentName());
} else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
keyBuilder.append('.');
fromXContent(parser, keyBuilder, builder, allowNullValues);
} else if (parser.currentToken() == XContentParser.Token.START_ARRAY) {
List<String> list = new ArrayList<>();
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
list.add(parser.text());
} else if (parser.currentToken() == XContentParser.Token.VALUE_NUMBER) {
list.add(parser.text()); // just use the string representation here
} else if (parser.currentToken() == XContentParser.Token.VALUE_BOOLEAN) {
list.add(String.valueOf(parser.text()));
} else {
throw new IllegalStateException("only value lists are allowed in serialized settings");
}
}
String key = keyBuilder.toString();
validateValue(key, list, parser, allowNullValues);
builder.putList(key, list);
} else if (parser.currentToken() == XContentParser.Token.VALUE_NULL) {
String key = keyBuilder.toString();
validateValue(key, null, parser, allowNullValues);
builder.putNull(key);
} else if (parser.currentToken() == XContentParser.Token.VALUE_STRING
|| parser.currentToken() == XContentParser.Token.VALUE_NUMBER) {
String key = keyBuilder.toString();
String value = parser.text();
validateValue(key, value, parser, allowNullValues);
builder.put(key, value);
} else if (parser.currentToken() == XContentParser.Token.VALUE_BOOLEAN) {
String key = keyBuilder.toString();
validateValue(key, parser.text(), parser, allowNullValues);
builder.put(key, parser.booleanValue());
} else {
XContentParserUtils.throwUnknownToken(parser.currentToken(), parser.getTokenLocation());
}
}
}
private static void validateValue(String key, Object currentValue, XContentParser parser, boolean allowNullValues) {
if (currentValue == null && allowNullValues == false) {
throw new OpenSearchParseException(
"null-valued setting found for key [{}] found at line number [{}], column number [{}]",
key,
parser.getTokenLocation().lineNumber,
parser.getTokenLocation().columnNumber
);
}
}
public static final Set<String> FORMAT_PARAMS = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList("settings_filter", "flat_settings"))
);
/**
* Returns {@code true} if this settings object contains no settings
* @return {@code true} if this settings object contains no settings
*/
public boolean isEmpty() {
return this.settings.isEmpty() && (secureSettings == null || secureSettings.getSettingNames().isEmpty());
}
/** Returns the number of settings in this settings object. */
public int size() {
return keySet().size();
}
/** Returns the fully qualified setting names contained in this settings object. */
public Set<String> keySet() {
if (keys.get() == null) {
synchronized (keys) {
// Check that the keys are still null now that we have acquired the lock
if (keys.get() == null) {
if (secureSettings == null) {
keys.set(settings.keySet());
} else {
Stream<String> stream = Stream.concat(settings.keySet().stream(), secureSettings.getSettingNames().stream());
// uniquify, since for legacy reasons the same setting name may exist in both
keys.set(Collections.unmodifiableSet(stream.collect(Collectors.toSet())));
}
}
}
}
return keys.get();
}
/**
* A builder allowing to put different settings and then {@link #build()} an immutable
* settings implementation. Use {@link Settings#builder()} in order to
* construct it.
*
* @opensearch.internal
*/
public static class Builder {
public static final Settings EMPTY_SETTINGS = new Builder().build();
// we use a sorted map for consistent serialization when using getAsMap()
private final Map<String, Object> map = new TreeMap<>();
private final SetOnce<SecureSettings> secureSettings = new SetOnce<>();
private Builder() {
}
public Set<String> keys() {
return this.map.keySet();
}
/**
* Removes the provided setting from the internal map holding the current list of settings.
*/
public String remove(String key) {
return Settings.toString(map.remove(key));
}
/**
* Returns a setting value based on the setting key.
*/
public String get(String key) {
return Settings.toString(map.get(key));
}
/** Return the current secure settings, or {@code null} if none have been set. */
public SecureSettings getSecureSettings() {
return secureSettings.get();
}
public Builder setSecureSettings(SecureSettings secureSettings) {
if (secureSettings.isLoaded() == false) {
throw new IllegalStateException("Secure settings must already be loaded");
}
if (this.secureSettings.get() != null) {
throw new IllegalArgumentException(
"Secure settings already set. Existing settings: "
+ this.secureSettings.get().getSettingNames()
+ ", new settings: "
+ secureSettings.getSettingNames()
);
}
this.secureSettings.set(secureSettings);
return this;
}
/**
* Sets a path setting with the provided setting key and path.
*
* @param key The setting key
* @param path The setting path
* @return The builder
*/
public Builder put(String key, Path path) {
return put(key, path.toString());
}
/**
* Sets a time value setting with the provided setting key and value.
*
* @param key The setting key
* @param timeValue The setting timeValue
* @return The builder
*/
public Builder put(final String key, final TimeValue timeValue) {
return put(key, timeValue.getStringRep());
}
/**
* Sets a byteSizeValue setting with the provided setting key and byteSizeValue.
*
* @param key The setting key
* @param byteSizeValue The setting value
* @return The builder
*/
public Builder put(final String key, final ByteSizeValue byteSizeValue) {
return put(key, byteSizeValue.getStringRep());
}
/**
* Sets an enum setting with the provided setting key and enum instance.
*
* @param key The setting key
* @param enumValue The setting value
* @return The builder
*/
public Builder put(String key, Enum<?> enumValue) {
return put(key, enumValue.toString());
}
/**
* Sets an level setting with the provided setting key and level instance.
*
* @param key The setting key
* @param level The setting value
* @return The builder
*/
public Builder put(String key, Level level) {
return put(key, level.toString());
}
/**
* Sets an lucene version setting with the provided setting key and lucene version instance.
*
* @param key The setting key
* @param luceneVersion The setting value
* @return The builder
*/
public Builder put(String key, org.apache.lucene.util.Version luceneVersion) {
return put(key, luceneVersion.toString());
}
/**
* Sets a setting with the provided setting key and value.
*
* @param key The setting key
* @param value The setting value
* @return The builder
*/
public Builder put(String key, String value) {
map.put(key, value);
return this;
}
public Builder copy(String key, Settings source) {
return copy(key, key, source);
}
public Builder copy(String key, String sourceKey, Settings source) {
if (source.settings.containsKey(sourceKey) == false) {
throw new IllegalArgumentException("source key not found in the source settings");
}
final Object value = source.settings.get(sourceKey);
if (value instanceof List) {
return putList(key, (List) value);
} else if (value == null) {
return putNull(key);
} else {
return put(key, Settings.toString(value));
}
}
/**
* Sets a null value for the given setting key
*/
public Builder putNull(String key) {
return put(key, (String) null);
}
/**
* Sets the setting with the provided setting key and the boolean value.
*
* @param setting The setting key
* @param value The boolean value
* @return The builder
*/
public Builder put(String setting, boolean value) {
put(setting, String.valueOf(value));
return this;
}
/**
* Sets the setting with the provided setting key and the int value.
*
* @param setting The setting key
* @param value The int value
* @return The builder
*/
public Builder put(String setting, int value) {
put(setting, String.valueOf(value));
return this;
}
public Builder put(String setting, Version version) {
put(setting, version.id);
return this;
}
/**
* Sets the setting with the provided setting key and the long value.
*
* @param setting The setting key
* @param value The long value
* @return The builder
*/
public Builder put(String setting, long value) {
put(setting, String.valueOf(value));
return this;
}
/**
* Sets the setting with the provided setting key and the float value.
*
* @param setting The setting key
* @param value The float value
* @return The builder
*/
public Builder put(String setting, float value) {
put(setting, String.valueOf(value));
return this;
}
/**
* Sets the setting with the provided setting key and the double value.
*
* @param setting The setting key
* @param value The double value
* @return The builder
*/
public Builder put(String setting, double value) {
put(setting, String.valueOf(value));
return this;
}
/**
* Sets the setting with the provided setting key and the time value.
*
* @param setting The setting key
* @param value The time value
* @return The builder
*/
public Builder put(final String setting, final long value, final TimeUnit timeUnit) {
put(setting, new TimeValue(value, timeUnit));
return this;
}
/**
* Sets the setting with the provided setting key and the size value.
*
* @param setting The setting key
* @param value The size value
* @return The builder
*/
public Builder put(String setting, long value, ByteSizeUnit sizeUnit) {
put(setting, sizeUnit.toBytes(value) + "b");
return this;
}
/**
* Sets the setting with the provided setting key and an array of values.
*