diff --git a/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/InstallPluginCommand.java b/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/InstallPluginCommand.java index fc2da33c3a688..06b1aae2bce32 100644 --- a/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/InstallPluginCommand.java +++ b/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/InstallPluginCommand.java @@ -44,6 +44,8 @@ import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.hash.MessageDigests; +import org.elasticsearch.common.io.Streams; +import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.env.Environment; @@ -52,6 +54,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; @@ -82,7 +85,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.TreeSet; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -130,36 +132,28 @@ class InstallPluginCommand extends EnvironmentAwareCommand { static final int PLUGIN_MALFORMED = 2; /** The builtin modules, which are plugins, but cannot be installed or removed. */ - static final Set MODULES; + private static final Set MODULES; static { - try (InputStream stream = InstallPluginCommand.class.getResourceAsStream("/modules.txt"); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { - Set modules = new HashSet<>(); - String line = reader.readLine(); - while (line != null) { - modules.add(line.trim()); - line = reader.readLine(); - } - MODULES = Collections.unmodifiableSet(modules); - } catch (IOException e) { - throw new RuntimeException(e); + try (var stream = InstallPluginCommand.class.getResourceAsStream("/modules.txt")) { + MODULES = Streams.readAllLines(stream) + .stream() + .map(String::trim) + .collect(Collectors.toUnmodifiableSet()); + } catch (final IOException e) { + throw new UncheckedIOException(e); } } /** The official plugins that can be installed simply by name. */ static final Set OFFICIAL_PLUGINS; static { - try (InputStream stream = InstallPluginCommand.class.getResourceAsStream("/plugins.txt"); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { - Set plugins = new TreeSet<>(); // use tree set to get sorting for help command - String line = reader.readLine(); - while (line != null) { - plugins.add(line.trim()); - line = reader.readLine(); - } - OFFICIAL_PLUGINS = Collections.unmodifiableSet(plugins); - } catch (IOException e) { - throw new RuntimeException(e); + try (var stream = InstallPluginCommand.class.getResourceAsStream("/plugins.txt")) { + OFFICIAL_PLUGINS = Streams.readAllLines(stream) + .stream() + .map(String::trim) + .collect(Sets.toUnmodifiableSortedSet()); + } catch (final IOException e) { + throw new UncheckedIOException(e); } } diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzerProvider.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzerProvider.java index 6eec01570a881..c7706391557cd 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzerProvider.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzerProvider.java @@ -29,11 +29,8 @@ import org.elasticsearch.index.analysis.AbstractIndexAnalyzerProvider; import org.elasticsearch.index.analysis.Analysis; -import java.util.HashMap; import java.util.Map; -import static java.util.Collections.unmodifiableMap; - /** * Creates a SnowballAnalyzer initialized with stopwords and Snowball filter. Only * supports Dutch, English (default), French, German and German2 where stopwords @@ -48,17 +45,12 @@ * */ public class SnowballAnalyzerProvider extends AbstractIndexAnalyzerProvider { - private static final Map DEFAULT_LANGUAGE_STOPWORDS; - - static { - Map defaultLanguageStopwords = new HashMap<>(); - defaultLanguageStopwords.put("English", EnglishAnalyzer.ENGLISH_STOP_WORDS_SET); - defaultLanguageStopwords.put("Dutch", DutchAnalyzer.getDefaultStopSet()); - defaultLanguageStopwords.put("German", GermanAnalyzer.getDefaultStopSet()); - defaultLanguageStopwords.put("German2", GermanAnalyzer.getDefaultStopSet()); - defaultLanguageStopwords.put("French", FrenchAnalyzer.getDefaultStopSet()); - DEFAULT_LANGUAGE_STOPWORDS = unmodifiableMap(defaultLanguageStopwords); - } + private static final Map DEFAULT_LANGUAGE_STOP_WORDS = Map.of( + "English", EnglishAnalyzer.ENGLISH_STOP_WORDS_SET, + "Dutch", DutchAnalyzer.getDefaultStopSet(), + "German", GermanAnalyzer.getDefaultStopSet(), + "German2", GermanAnalyzer.getDefaultStopSet(), + "French", FrenchAnalyzer.getDefaultStopSet()); private final SnowballAnalyzer analyzer; @@ -66,7 +58,7 @@ public class SnowballAnalyzerProvider extends AbstractIndexAnalyzerProvider, BiFunction> queryProcessors; - - static { - Map, BiFunction> map = new HashMap<>(); - map.put(MatchNoDocsQuery.class, matchNoDocsQuery()); - map.put(MatchAllDocsQuery.class, matchAllDocsQuery()); - map.put(ConstantScoreQuery.class, constantScoreQuery()); - map.put(BoostQuery.class, boostQuery()); - map.put(TermQuery.class, termQuery()); - map.put(TermInSetQuery.class, termInSetQuery()); - map.put(CommonTermsQuery.class, commonTermsQuery()); - map.put(BlendedTermQuery.class, blendedTermQuery()); - map.put(PhraseQuery.class, phraseQuery()); - map.put(MultiPhraseQuery.class, multiPhraseQuery()); - map.put(SpanTermQuery.class, spanTermQuery()); - map.put(SpanNearQuery.class, spanNearQuery()); - map.put(SpanOrQuery.class, spanOrQuery()); - map.put(SpanFirstQuery.class, spanFirstQuery()); - map.put(SpanNotQuery.class, spanNotQuery()); - map.put(BooleanQuery.class, booleanQuery()); - map.put(DisjunctionMaxQuery.class, disjunctionMaxQuery()); - map.put(SynonymQuery.class, synonymQuery()); - map.put(FunctionScoreQuery.class, functionScoreQuery()); - map.put(PointRangeQuery.class, pointRangeQuery()); - map.put(IndexOrDocValuesQuery.class, indexOrDocValuesQuery()); - map.put(ESToParentBlockJoinQuery.class, toParentBlockJoinQuery()); - queryProcessors = Collections.unmodifiableMap(map); - } + private static final Map, BiFunction> QUERY_PROCESSORS = Map.ofEntries( + entry(MatchNoDocsQuery.class, matchNoDocsQuery()), + entry(MatchAllDocsQuery.class, matchAllDocsQuery()), + entry(ConstantScoreQuery.class, constantScoreQuery()), + entry(BoostQuery.class, boostQuery()), + entry(TermQuery.class, termQuery()), + entry(TermInSetQuery.class, termInSetQuery()), + entry(CommonTermsQuery.class, commonTermsQuery()), + entry(BlendedTermQuery.class, blendedTermQuery()), + entry(PhraseQuery.class, phraseQuery()), + entry(MultiPhraseQuery.class, multiPhraseQuery()), + entry(SpanTermQuery.class, spanTermQuery()), + entry(SpanNearQuery.class, spanNearQuery()), + entry(SpanOrQuery.class, spanOrQuery()), + entry(SpanFirstQuery.class, spanFirstQuery()), + entry(SpanNotQuery.class, spanNotQuery()), + entry(BooleanQuery.class, booleanQuery()), + entry(DisjunctionMaxQuery.class, disjunctionMaxQuery()), + entry(SynonymQuery.class, synonymQuery()), + entry(FunctionScoreQuery.class, functionScoreQuery()), + entry(PointRangeQuery.class, pointRangeQuery()), + entry(IndexOrDocValuesQuery.class, indexOrDocValuesQuery()), + entry(ESToParentBlockJoinQuery.class, toParentBlockJoinQuery())); private QueryAnalyzer() { } @@ -130,11 +125,11 @@ private QueryAnalyzer() { static Result analyze(Query query, Version indexVersion) { Class queryClass = query.getClass(); if (queryClass.isAnonymousClass()) { - // Sometimes queries have anonymous classes in that case we need the direct super class. - // (for example blended term query) + // sometimes queries have anonymous classes in that case we need the direct super class (e.g., blended term query) queryClass = queryClass.getSuperclass(); } - BiFunction queryProcessor = queryProcessors.get(queryClass); + assert Query.class.isAssignableFrom(queryClass) : query.getClass(); + BiFunction queryProcessor = QUERY_PROCESSORS.get(queryClass); if (queryProcessor != null) { return queryProcessor.apply(query, indexVersion); } else { diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/TestDeprecationHeaderRestAction.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/TestDeprecationHeaderRestAction.java index 27b2f18b0919f..b609e28a2ac0b 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/TestDeprecationHeaderRestAction.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/TestDeprecationHeaderRestAction.java @@ -18,8 +18,8 @@ */ package org.elasticsearch.http; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.settings.Setting; @@ -33,8 +33,6 @@ import org.elasticsearch.rest.RestStatus; import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -58,17 +56,10 @@ public class TestDeprecationHeaderRestAction extends BaseRestHandler { Setting.boolSetting("test.setting.not_deprecated", false, Setting.Property.NodeScope, Setting.Property.Dynamic); - private static final Map> SETTINGS_MAP; - - static { - Map> settingsMap = new HashMap<>(3); - - settingsMap.put(TEST_DEPRECATED_SETTING_TRUE1.getKey(), TEST_DEPRECATED_SETTING_TRUE1); - settingsMap.put(TEST_DEPRECATED_SETTING_TRUE2.getKey(), TEST_DEPRECATED_SETTING_TRUE2); - settingsMap.put(TEST_NOT_DEPRECATED_SETTING.getKey(), TEST_NOT_DEPRECATED_SETTING); - - SETTINGS_MAP = Collections.unmodifiableMap(settingsMap); - } + private static final Map> SETTINGS_MAP = Map.of( + TEST_DEPRECATED_SETTING_TRUE1.getKey(), TEST_DEPRECATED_SETTING_TRUE1, + TEST_DEPRECATED_SETTING_TRUE2.getKey(), TEST_DEPRECATED_SETTING_TRUE2, + TEST_NOT_DEPRECATED_SETTING.getKey(), TEST_NOT_DEPRECATED_SETTING); public static final String DEPRECATED_ENDPOINT = "[/_test_cluster/deprecated_settings] exists for deprecated tests"; public static final String DEPRECATED_USAGE = "[deprecated_settings] usage is deprecated. use [settings] instead"; diff --git a/server/src/main/java/org/elasticsearch/cluster/coordination/Reconfigurator.java b/server/src/main/java/org/elasticsearch/cluster/coordination/Reconfigurator.java index 44e6532df2daa..81a12ea4d47b4 100644 --- a/server/src/main/java/org/elasticsearch/cluster/coordination/Reconfigurator.java +++ b/server/src/main/java/org/elasticsearch/cluster/coordination/Reconfigurator.java @@ -123,7 +123,7 @@ public VotingConfiguration reconfigure(Set liveNodes, Set final Set liveInConfigIds = new TreeSet<>(currentConfig.getNodeIds()); liveInConfigIds.retainAll(liveNodeIds); - final Set inConfigNotLiveIds = Sets.sortedDifference(currentConfig.getNodeIds(), liveInConfigIds); + final Set inConfigNotLiveIds = Sets.unmodifiableSortedDifference(currentConfig.getNodeIds(), liveInConfigIds); final Set nonRetiredInConfigNotLiveIds = new TreeSet<>(inConfigNotLiveIds); nonRetiredInConfigNotLiveIds.removeAll(retiredNodeIds); diff --git a/server/src/main/java/org/elasticsearch/common/inject/internal/MoreTypes.java b/server/src/main/java/org/elasticsearch/common/inject/internal/MoreTypes.java index 7e4d54867fb30..8ae2248f9ea8b 100644 --- a/server/src/main/java/org/elasticsearch/common/inject/internal/MoreTypes.java +++ b/server/src/main/java/org/elasticsearch/common/inject/internal/MoreTypes.java @@ -32,13 +32,11 @@ import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; -import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import static java.util.Collections.singleton; -import static java.util.Collections.unmodifiableMap; /** * Static methods for working with types that we aren't publishing in the @@ -53,20 +51,16 @@ public class MoreTypes { private MoreTypes() { } - private static final Map, TypeLiteral> PRIMITIVE_TO_WRAPPER; - static { - Map, TypeLiteral> primitiveToWrapper = new HashMap<>(); - primitiveToWrapper.put(TypeLiteral.get(boolean.class), TypeLiteral.get(Boolean.class)); - primitiveToWrapper.put(TypeLiteral.get(byte.class), TypeLiteral.get(Byte.class)); - primitiveToWrapper.put(TypeLiteral.get(short.class), TypeLiteral.get(Short.class)); - primitiveToWrapper.put(TypeLiteral.get(int.class), TypeLiteral.get(Integer.class)); - primitiveToWrapper.put(TypeLiteral.get(long.class), TypeLiteral.get(Long.class)); - primitiveToWrapper.put(TypeLiteral.get(float.class), TypeLiteral.get(Float.class)); - primitiveToWrapper.put(TypeLiteral.get(double.class), TypeLiteral.get(Double.class)); - primitiveToWrapper.put(TypeLiteral.get(char.class), TypeLiteral.get(Character.class)); - primitiveToWrapper.put(TypeLiteral.get(void.class), TypeLiteral.get(Void.class)); - PRIMITIVE_TO_WRAPPER = unmodifiableMap(primitiveToWrapper); - } + private static final Map, TypeLiteral> PRIMITIVE_TO_WRAPPER = Map.of( + TypeLiteral.get(boolean.class), TypeLiteral.get(Boolean.class), + TypeLiteral.get(byte.class), TypeLiteral.get(Byte.class), + TypeLiteral.get(short.class), TypeLiteral.get(Short.class), + TypeLiteral.get(int.class), TypeLiteral.get(Integer.class), + TypeLiteral.get(long.class), TypeLiteral.get(Long.class), + TypeLiteral.get(float.class), TypeLiteral.get(Float.class), + TypeLiteral.get(double.class), TypeLiteral.get(Double.class), + TypeLiteral.get(char.class), TypeLiteral.get(Character.class), + TypeLiteral.get(void.class), TypeLiteral.get(Void.class)); /** * Returns an equivalent type that's safe for use in a key. The returned type will be free of diff --git a/server/src/main/java/org/elasticsearch/common/util/set/Sets.java b/server/src/main/java/org/elasticsearch/common/util/set/Sets.java index 950d6433510bf..9ab4ee59b4189 100644 --- a/server/src/main/java/org/elasticsearch/common/util/set/Sets.java +++ b/server/src/main/java/org/elasticsearch/common/util/set/Sets.java @@ -96,13 +96,50 @@ public static Set difference(Set left, Set right) { * @param the type of the elements of the sets * @return the sorted relative complement of the left set with respect to the right set */ - public static SortedSet sortedDifference(Set left, Set right) { + public static SortedSet sortedDifference(final Set left, final Set right) { Objects.requireNonNull(left); Objects.requireNonNull(right); - return left.stream().filter(k -> !right.contains(k)).collect(new SortedSetCollector<>()); + return left.stream().filter(k -> right.contains(k) == false).collect(toSortedSet()); } - private static class SortedSetCollector implements Collector, SortedSet> { + /** + * The relative complement, or difference, of the specified left and right set, returned as a sorted set. Namely, the resulting set + * contains all the elements that are in the left set but not in the right set, and the set is sorted using the natural ordering of + * element type. Neither input is mutated by this operation, an entirely new set is returned. The resulting set is unmodifiable. + * + * @param left the left set + * @param right the right set + * @param the type of the elements of the sets + * @return the unmodifiable sorted relative complement of the left set with respect to the right set + */ + public static Set unmodifiableSortedDifference(final Set left, final Set right) { + Objects.requireNonNull(left); + Objects.requireNonNull(right); + return left.stream().filter(k -> right.contains(k) == false).collect(toUnmodifiableSortedSet()); + } + + /** + * Returns a {@link Collector} that accumulates the input elements into a sorted set. + * + * @param the type of the input elements + * @return a sorted set + */ + public static Collector, SortedSet> toSortedSet() { + return new SortedSetCollector<>(); + } + + /** + * Returns a {@link Collector} that accumulates the input elements into a sorted set and finishes the resulting set into an + * unmodifiable set. The resulting read-only view through the unmodifiable set is a sorted set. + * + * @param the type of the input elements + * @return an unmodifiable set where the underlying set is sorted + */ + public static Collector, Set> toUnmodifiableSortedSet() { + return new UnmodifiableSortedSetCollector<>(); + } + + abstract static class AbstractSortedSetCollector> implements Collector, R> { @Override public Supplier> supplier() { @@ -111,7 +148,7 @@ public Supplier> supplier() { @Override public BiConsumer, T> accumulator() { - return (s, e) -> s.add(e); + return SortedSet::add; } @Override @@ -122,13 +159,21 @@ public BinaryOperator> combiner() { }; } + public abstract Function, R> finisher(); + + public abstract Set characteristics(); + + } + + private static class SortedSetCollector extends AbstractSortedSetCollector> { + @Override public Function, SortedSet> finisher() { return Function.identity(); } static final Set CHARACTERISTICS = - Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); + Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); @Override public Set characteristics() { @@ -137,6 +182,20 @@ public Set characteristics() { } + private static class UnmodifiableSortedSetCollector extends AbstractSortedSetCollector> { + + @Override + public Function, Set> finisher() { + return Collections::unmodifiableSet; + } + + @Override + public Set characteristics() { + return Collections.emptySet(); + } + + } + public static Set union(Set left, Set right) { Objects.requireNonNull(left); Objects.requireNonNull(right); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestGetMappingAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestGetMappingAction.java index 74f451ab30cd2..a1854eaf27e6d 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestGetMappingAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestGetMappingAction.java @@ -20,7 +20,6 @@ package org.elasticsearch.rest.action.admin.indices; import com.carrotsearch.hppc.cursors.ObjectCursor; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest; @@ -51,7 +50,6 @@ import java.util.List; import java.util.Locale; import java.util.Set; -import java.util.SortedSet; import java.util.stream.Collectors; import static org.elasticsearch.rest.RestRequest.Method.GET; @@ -118,7 +116,7 @@ public RestResponse buildResponse(final GetMappingsResponse response, final XCon } } - final SortedSet difference = Sets.sortedDifference(Arrays.stream(types).collect(Collectors.toSet()), typeNames); + final Set difference = Sets.sortedDifference(Arrays.stream(types).collect(Collectors.toSet()), typeNames); // now remove requested aliases that contain wildcards that are simple matches final List matches = new ArrayList<>(); diff --git a/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java b/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java index 56053476fa22f..3468d3d30212b 100644 --- a/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java +++ b/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java @@ -42,6 +42,7 @@ import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -55,9 +56,11 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Collections.unmodifiableMap; +import static java.util.Map.entry; public class ThreadPool implements Scheduler, Closeable { @@ -98,15 +101,8 @@ public String getType() { this.type = type; } - private static final Map TYPE_MAP; - - static { - Map typeMap = new HashMap<>(); - for (ThreadPoolType threadPoolType : ThreadPoolType.values()) { - typeMap.put(threadPoolType.getType(), threadPoolType); - } - TYPE_MAP = Collections.unmodifiableMap(typeMap); - } + private static final Map TYPE_MAP = + Arrays.stream(ThreadPoolType.values()).collect(Collectors.toUnmodifiableMap(ThreadPoolType::getType, Function.identity())); public static ThreadPoolType fromType(String type) { ThreadPoolType threadPoolType = TYPE_MAP.get(type); @@ -117,28 +113,23 @@ public static ThreadPoolType fromType(String type) { } } - public static final Map THREAD_POOL_TYPES; - - static { - HashMap map = new HashMap<>(); - map.put(Names.SAME, ThreadPoolType.DIRECT); - map.put(Names.GENERIC, ThreadPoolType.SCALING); - map.put(Names.LISTENER, ThreadPoolType.FIXED); - map.put(Names.GET, ThreadPoolType.FIXED); - map.put(Names.ANALYZE, ThreadPoolType.FIXED); - map.put(Names.WRITE, ThreadPoolType.FIXED); - map.put(Names.SEARCH, ThreadPoolType.FIXED_AUTO_QUEUE_SIZE); - map.put(Names.MANAGEMENT, ThreadPoolType.SCALING); - map.put(Names.FLUSH, ThreadPoolType.SCALING); - map.put(Names.REFRESH, ThreadPoolType.SCALING); - map.put(Names.WARMER, ThreadPoolType.SCALING); - map.put(Names.SNAPSHOT, ThreadPoolType.SCALING); - map.put(Names.FORCE_MERGE, ThreadPoolType.FIXED); - map.put(Names.FETCH_SHARD_STARTED, ThreadPoolType.SCALING); - map.put(Names.FETCH_SHARD_STORE, ThreadPoolType.SCALING); - map.put(Names.SEARCH_THROTTLED, ThreadPoolType.FIXED_AUTO_QUEUE_SIZE); - THREAD_POOL_TYPES = Collections.unmodifiableMap(map); - } + public static final Map THREAD_POOL_TYPES = Map.ofEntries( + entry(Names.SAME, ThreadPoolType.DIRECT), + entry(Names.GENERIC, ThreadPoolType.SCALING), + entry(Names.LISTENER, ThreadPoolType.FIXED), + entry(Names.GET, ThreadPoolType.FIXED), + entry(Names.ANALYZE, ThreadPoolType.FIXED), + entry(Names.WRITE, ThreadPoolType.FIXED), + entry(Names.SEARCH, ThreadPoolType.FIXED_AUTO_QUEUE_SIZE), + entry(Names.MANAGEMENT, ThreadPoolType.SCALING), + entry(Names.FLUSH, ThreadPoolType.SCALING), + entry(Names.REFRESH, ThreadPoolType.SCALING), + entry(Names.WARMER, ThreadPoolType.SCALING), + entry(Names.SNAPSHOT, ThreadPoolType.SCALING), + entry(Names.FORCE_MERGE, ThreadPoolType.FIXED), + entry(Names.FETCH_SHARD_STARTED, ThreadPoolType.SCALING), + entry(Names.FETCH_SHARD_STORE, ThreadPoolType.SCALING), + entry(Names.SEARCH_THROTTLED, ThreadPoolType.FIXED_AUTO_QUEUE_SIZE)); private final Map executors; diff --git a/server/src/test/java/org/elasticsearch/common/util/set/SetsTests.java b/server/src/test/java/org/elasticsearch/common/util/set/SetsTests.java index f4337daf4346c..df6f264bdd58d 100644 --- a/server/src/test/java/org/elasticsearch/common/util/set/SetsTests.java +++ b/server/src/test/java/org/elasticsearch/common/util/set/SetsTests.java @@ -25,6 +25,8 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -42,9 +44,21 @@ public void testDifference() { } public void testSortedDifference() { + runSortedDifferenceTest(Sets::sortedDifference, set -> {}); + } + + public void testUnmodifiableSortedDifference() { + runSortedDifferenceTest( + // assert the resulting difference us unmodifiable + Sets::unmodifiableSortedDifference, set -> expectThrows(UnsupportedOperationException.class, () -> set.add(randomInt()))); + } + + private void runSortedDifferenceTest( + final BiFunction, Set, Set> sortedDifference, + final Consumer> asserter) { final int endExclusive = randomIntBetween(0, 256); final Tuple, Set> sets = randomSets(endExclusive); - final Set difference = Sets.sortedDifference(sets.v1(), sets.v2()); + final Set difference = sortedDifference.apply(sets.v1(), sets.v2()); assertDifference(endExclusive, sets, difference); final Iterator it = difference.iterator(); if (it.hasNext()) { @@ -55,6 +69,7 @@ public void testSortedDifference() { current = next; } } + asserter.accept(difference); } public void testIntersection() { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java index 6391251bbcb26..cd1f999c1004e 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java @@ -13,7 +13,6 @@ import java.io.IOException; import java.time.ZoneOffset; import java.util.Calendar; -import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; @@ -23,6 +22,7 @@ import java.util.TimeZone; import java.util.TreeSet; +import static java.util.Map.entry; import static org.elasticsearch.xpack.core.watcher.support.Exceptions.illegalArgument; @@ -213,30 +213,28 @@ public class Cron implements ToXContentFragment { private static final Integer ALL_SPEC = ALL_SPEC_INT; private static final Integer NO_SPEC = NO_SPEC_INT; - private static final Map monthMap = new HashMap<>(20); - private static final Map dayMap = new HashMap<>(60); - static { - monthMap.put("JAN", 0); - monthMap.put("FEB", 1); - monthMap.put("MAR", 2); - monthMap.put("APR", 3); - monthMap.put("MAY", 4); - monthMap.put("JUN", 5); - monthMap.put("JUL", 6); - monthMap.put("AUG", 7); - monthMap.put("SEP", 8); - monthMap.put("OCT", 9); - monthMap.put("NOV", 10); - monthMap.put("DEC", 11); - - dayMap.put("SUN", 1); - dayMap.put("MON", 2); - dayMap.put("TUE", 3); - dayMap.put("WED", 4); - dayMap.put("THU", 5); - dayMap.put("FRI", 6); - dayMap.put("SAT", 7); - } + private static final Map MONTH_MAP = Map.ofEntries( + entry("JAN", 0), + entry("FEB", 1), + entry("MAR", 2), + entry("APR", 3), + entry("MAY", 4), + entry("JUN", 5), + entry("JUL", 6), + entry("AUG", 7), + entry("SEP", 8), + entry("OCT", 9), + entry("NOV", 10), + entry("DEC", 11)); + + private static final Map DAY_MAP = Map.of( + "SUN", 1, + "MON", 2, + "TUE", 3, + "WED", 4, + "THU", 5, + "FRI", 6, + "SAT", 7); private final String expression; @@ -1413,7 +1411,7 @@ private int getNumericValue(String s, int i) { } private int getMonthNumber(String s) { - Integer integer = monthMap.get(s); + Integer integer = MONTH_MAP.get(s); if (integer == null) { return -1; @@ -1423,7 +1421,7 @@ private int getMonthNumber(String s) { } private int getDayOfWeekNumber(String s) { - Integer integer = dayMap.get(s); + Integer integer = DAY_MAP.get(s); if (integer == null) { return -1; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/persistence/DatafeedConfigProvider.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/persistence/DatafeedConfigProvider.java index 1c0d6dea5988d..d24b91d07cef0 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/persistence/DatafeedConfigProvider.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/persistence/DatafeedConfigProvider.java @@ -45,20 +45,18 @@ import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.xpack.core.ClientHelper; +import org.elasticsearch.xpack.core.action.util.ExpandedIdsMatcher; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedUpdate; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndex; import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper; import org.elasticsearch.xpack.core.ml.utils.ToXContentParams; -import org.elasticsearch.xpack.core.action.util.ExpandedIdsMatcher; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -86,13 +84,9 @@ public class DatafeedConfigProvider { private final Client client; private final NamedXContentRegistry xContentRegistry; - public static final Map TO_XCONTENT_PARAMS; - static { - Map modifiable = new HashMap<>(); - modifiable.put(ToXContentParams.FOR_INTERNAL_STORAGE, "true"); - modifiable.put(ToXContentParams.INCLUDE_TYPE, "true"); - TO_XCONTENT_PARAMS = Collections.unmodifiableMap(modifiable); - } + public static final Map TO_XCONTENT_PARAMS = Map.of( + ToXContentParams.FOR_INTERNAL_STORAGE, "true", + ToXContentParams.INCLUDE_TYPE, "true"); public DatafeedConfigProvider(Client client, NamedXContentRegistry xContentRegistry) { this.client = client; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeController.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeController.java index 721e07721e32d..2dc86825a1209 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeController.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeController.java @@ -17,8 +17,6 @@ import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; @@ -43,14 +41,7 @@ public class NativeController { private static final String START_COMMAND = "start"; private static final String KILL_COMMAND = "kill"; - public static final Map UNKNOWN_NATIVE_CODE_INFO; - - static { - Map unknownInfo = new HashMap<>(2); - unknownInfo.put("version", "N/A"); - unknownInfo.put("build_hash", "N/A"); - UNKNOWN_NATIVE_CODE_INFO = Collections.unmodifiableMap(unknownInfo); - } + public static final Map UNKNOWN_NATIVE_CODE_INFO = Map.of("version", "N/A", "build_hash", "N/A"); private final CppLogMessageHandler cppLogHandler; private final OutputStream commandStream; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/DomainSplitFunction.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/DomainSplitFunction.java index 62ee074aecdfa..452c1f5e9ed81 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/DomainSplitFunction.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/DomainSplitFunction.java @@ -9,16 +9,18 @@ import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.logging.DeprecationLogger; -import java.io.InputStream; +import java.io.IOException; +import java.io.UncheckedIOException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringJoiner; +import java.util.stream.Collectors; + +import static java.util.Map.entry; public final class DomainSplitFunction { @@ -28,68 +30,60 @@ public final class DomainSplitFunction { private static final int MAX_DOMAIN_PART_LENGTH = 63; private static final Map exact; - private static final Map under; - private static final Map excluded; - static { - Map exactMap = new HashMap<>(2048); - - String exactResourceName = "org/elasticsearch/xpack/ml/transforms/exact.properties"; + private static final Map under = Map.ofEntries( + entry("bd", "i"), + entry("np", "i"), + entry("jm", "i"), + entry("fj", "i"), + entry("fk", "i"), + entry("ye", "i"), + entry("sch.uk", "i"), + entry("bn", "i"), + entry("kitakyushu.jp", "i"), + entry("kobe.jp", "i"), + entry("ke", "i"), + entry("sapporo.jp", "i"), + entry("kh", "i"), + entry("mm", "i"), + entry("il", "i"), + entry("yokohama.jp", "i"), + entry("ck", "i"), + entry("nagoya.jp", "i"), + entry("sendai.jp", "i"), + entry("kw", "i"), + entry("er", "i"), + entry("mz", "i"), + entry("platform.sh", "p"), + entry("gu", "i"), + entry("nom.br", "i"), + entry("zm", "i"), + entry("pg", "i"), + entry("ni", "i"), + entry("kawasaki.jp", "i"), + entry("zw", "i")); + + private static final Map excluded = + Map.of( + "city.yokohama.jp", "i", + "teledata.mz", "i", + "city.kobe.jp", "i", + "city.sapporo.jp", "i", + "city.kawasaki.jp", "i", + "city.nagoya.jp", "i", + "www.ck", "i", + "city.sendai.jp", "i", + "city.kitakyushu.jp", "i"); - try (InputStream resource = DomainSplitFunction.class.getClassLoader().getResourceAsStream(exactResourceName)) { - List lines = Streams.readAllLines(resource); - for (String line : lines) { - String[] split = line.split("="); - exactMap.put(split[0].trim(), split[1].trim()); - } - } catch (Exception e) { - throw new RuntimeException("Could not load DomainSplit resource", e); + static { + try (var stream = + DomainSplitFunction.class.getClassLoader().getResourceAsStream("org/elasticsearch/xpack/ml/transforms/exact.properties")) { + exact = Streams.readAllLines(stream) + .stream() + .map(line -> line.split("=")) + .collect(Collectors.toUnmodifiableMap(split -> split[0], split -> split[1])); + } catch (final IOException e) { + throw new UncheckedIOException(e); } - exact = Collections.unmodifiableMap(exactMap); - - Map underMap = new HashMap<>(30); - underMap.put("bd", "i"); - underMap.put("np", "i"); - underMap.put("jm", "i"); - underMap.put("fj", "i"); - underMap.put("fk", "i"); - underMap.put("ye", "i"); - underMap.put("sch.uk", "i"); - underMap.put("bn", "i"); - underMap.put("kitakyushu.jp", "i"); - underMap.put("kobe.jp", "i"); - underMap.put("ke", "i"); - underMap.put("sapporo.jp", "i"); - underMap.put("kh", "i"); - underMap.put("mm", "i"); - underMap.put("il", "i"); - underMap.put("yokohama.jp", "i"); - underMap.put("ck", "i"); - underMap.put("nagoya.jp", "i"); - underMap.put("sendai.jp", "i"); - underMap.put("kw", "i"); - underMap.put("er", "i"); - underMap.put("mz", "i"); - underMap.put("platform.sh", "p"); - underMap.put("gu", "i"); - underMap.put("nom.br", "i"); - underMap.put("zm", "i"); - underMap.put("pg", "i"); - underMap.put("ni", "i"); - underMap.put("kawasaki.jp", "i"); - underMap.put("zw", "i"); - under = Collections.unmodifiableMap(underMap); - - Map excludedMap = new HashMap<>(9); - excludedMap.put("city.yokohama.jp", "i"); - excludedMap.put("teledata.mz", "i"); - excludedMap.put("city.kobe.jp", "i"); - excludedMap.put("city.sapporo.jp", "i"); - excludedMap.put("city.kawasaki.jp", "i"); - excludedMap.put("city.nagoya.jp", "i"); - excludedMap.put("www.ck", "i"); - excludedMap.put("city.sendai.jp", "i"); - excludedMap.put("city.kitakyushu.jp", "i"); - excluded = Collections.unmodifiableMap(excludedMap); } private DomainSplitFunction() {} diff --git a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTestCase.java b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTestCase.java index 6754b1acb9347..8245ecf36a627 100644 --- a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTestCase.java +++ b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTestCase.java @@ -21,13 +21,13 @@ import org.junit.BeforeClass; import javax.security.auth.Subject; + import java.io.IOException; import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; @@ -54,37 +54,33 @@ public abstract class KerberosTestCase extends ESTestCase { protected SimpleKdcLdapServer simpleKdcLdapServer; private static Locale restoreLocale; - private static Set unsupportedLocaleLanguages; - - static { - unsupportedLocaleLanguages = new HashSet<>(); - /* - * arabic and other languages have problem due to handling of GeneralizedTime in - * SimpleKdcServer For more look at : - * org.apache.kerby.asn1.type.Asn1GeneralizedTime#toBytes() - */ - unsupportedLocaleLanguages.add("ar"); - unsupportedLocaleLanguages.add("ja"); - unsupportedLocaleLanguages.add("th"); - unsupportedLocaleLanguages.add("hi"); - unsupportedLocaleLanguages.add("uz"); - unsupportedLocaleLanguages.add("fa"); - unsupportedLocaleLanguages.add("ks"); - unsupportedLocaleLanguages.add("ckb"); - unsupportedLocaleLanguages.add("ne"); - unsupportedLocaleLanguages.add("dz"); - unsupportedLocaleLanguages.add("mzn"); - unsupportedLocaleLanguages.add("mr"); - unsupportedLocaleLanguages.add("as"); - unsupportedLocaleLanguages.add("bn"); - unsupportedLocaleLanguages.add("lrc"); - unsupportedLocaleLanguages.add("my"); - unsupportedLocaleLanguages.add("ps"); - unsupportedLocaleLanguages.add("ur"); - unsupportedLocaleLanguages.add("pa"); - unsupportedLocaleLanguages.add("ig"); - unsupportedLocaleLanguages.add("sd"); - } + + /* + * Arabic and other language have problems due to handling of generalized time in SimpleKdcServer. For more, look at + * org.apache.kerby.asn1.type.Asn1GeneralizedTime#toBytes + */ + private static Set UNSUPPORTED_LOCALE_LANGUAGES = Set.of( + "ar", + "ja", + "th", + "hi", + "uz", + "fa", + "ks", + "ckb", + "ne", + "dz", + "mzn", + "mr", + "as", + "bn", + "lrc", + "my", + "ps", + "ur", + "pa", + "ig", + "sd"); @BeforeClass public static void setupKerberos() throws Exception { @@ -106,7 +102,7 @@ public static void restoreLocale() { } private static boolean isLocaleUnsupported() { - return unsupportedLocaleLanguages.contains(Locale.getDefault().getLanguage()); + return UNSUPPORTED_LOCALE_LANGUAGES.contains(Locale.getDefault().getLanguage()); } @Before