Browse Source

Use collections conveniences in static initializers (#41374)

This commit replaces the construction of some collections in static
initializers with new collection convenience methods that are available
now that we have bumped the minimum Java language level to be higher
than Java 8.
Jason Tedor 6 years ago
parent
commit
a5ad5f7bb9

+ 18 - 24
distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/InstallPluginCommand.java

@@ -44,6 +44,8 @@ import org.elasticsearch.cli.UserException;
 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.IOException;
 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.Locale;
 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<String> MODULES;
+    private static final Set<String> MODULES;
     static {
-        try (InputStream stream = InstallPluginCommand.class.getResourceAsStream("/modules.txt");
-            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
-            Set<String> 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<String> OFFICIAL_PLUGINS;
     static {
-        try (InputStream stream = InstallPluginCommand.class.getResourceAsStream("/plugins.txt");
-            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
-            Set<String> 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);
         }
     }
 

+ 7 - 15
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzerProvider.java

@@ -29,11 +29,8 @@ import org.elasticsearch.index.IndexSettings;
 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 @@ import static java.util.Collections.unmodifiableMap;
  *
  */
 public class SnowballAnalyzerProvider extends AbstractIndexAnalyzerProvider<SnowballAnalyzer> {
-    private static final Map<String, CharArraySet> DEFAULT_LANGUAGE_STOPWORDS;
-
-    static {
-        Map<String, CharArraySet> 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<String, CharArraySet> 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<Snow
         super(indexSettings, name, settings);
 
         String language = settings.get("language", settings.get("name", "English"));
-        CharArraySet defaultStopwords = DEFAULT_LANGUAGE_STOPWORDS.getOrDefault(language, CharArraySet.EMPTY_SET);
+        CharArraySet defaultStopwords = DEFAULT_LANGUAGE_STOP_WORDS.getOrDefault(language, CharArraySet.EMPTY_SET);
         CharArraySet stopWords = Analysis.parseStopWords(env, settings, defaultStopwords);
 
         analyzer = new SnowballAnalyzer(language, stopWords);

+ 27 - 32
modules/percolator/src/main/java/org/elasticsearch/percolator/QueryAnalyzer.java

@@ -55,7 +55,6 @@ import org.elasticsearch.index.search.ESToParentBlockJoinQuery;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -64,38 +63,34 @@ import java.util.Set;
 import java.util.function.BiFunction;
 import java.util.stream.Collectors;
 
+import static java.util.Map.entry;
 import static java.util.stream.Collectors.toSet;
 
 final class QueryAnalyzer {
 
-    private static final Map<Class<? extends Query>, BiFunction<Query, Version, Result>> queryProcessors;
-
-    static {
-        Map<Class<? extends Query>, BiFunction<Query, Version, Result>> 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<Class<? extends Query>, BiFunction<Query, Version, Result>> 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 @@ final class 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<Query, Version, Result> queryProcessor = queryProcessors.get(queryClass);
+        assert Query.class.isAssignableFrom(queryClass) : query.getClass();
+        BiFunction<Query, Version, Result> queryProcessor = QUERY_PROCESSORS.get(queryClass);
         if (queryProcessor != null) {
             return queryProcessor.apply(query, indexVersion);
         } else {

+ 5 - 14
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.RestRequest;
 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<String, Setting<?>> SETTINGS_MAP;
-
-    static {
-        Map<String, Setting<?>> 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<String, Setting<?>> 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";

+ 1 - 1
server/src/main/java/org/elasticsearch/cluster/coordination/Reconfigurator.java

@@ -123,7 +123,7 @@ public class Reconfigurator {
         final Set<String> liveInConfigIds = new TreeSet<>(currentConfig.getNodeIds());
         liveInConfigIds.retainAll(liveNodeIds);
 
-        final Set<String> inConfigNotLiveIds = Sets.sortedDifference(currentConfig.getNodeIds(), liveInConfigIds);
+        final Set<String> inConfigNotLiveIds = Sets.unmodifiableSortedDifference(currentConfig.getNodeIds(), liveInConfigIds);
         final Set<String> nonRetiredInConfigNotLiveIds = new TreeSet<>(inConfigNotLiveIds);
         nonRetiredInConfigNotLiveIds.removeAll(retiredNodeIds);
 

+ 10 - 16
server/src/main/java/org/elasticsearch/common/inject/internal/MoreTypes.java

@@ -32,13 +32,11 @@ import java.lang.reflect.Type;
 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<?>, TypeLiteral<?>> PRIMITIVE_TO_WRAPPER;
-    static {
-        Map<TypeLiteral<?>, 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<?>, 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

+ 64 - 5
server/src/main/java/org/elasticsearch/common/util/set/Sets.java

@@ -96,13 +96,50 @@ public final class Sets {
      * @param <T>   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 <T> SortedSet<T> sortedDifference(Set<T> left, Set<T> right) {
+    public static <T> SortedSet<T> sortedDifference(final Set<T> left, final Set<T> 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<T> implements Collector<T, SortedSet<T>, SortedSet<T>> {
+    /**
+     * 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 <T>   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 <T> Set<T> unmodifiableSortedDifference(final Set<T> left, final Set<T> 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 <T> the type of the input elements
+     * @return a sorted set
+     */
+    public static <T> Collector<T, SortedSet<T>, SortedSet<T>> 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 <T> the type of the input elements
+     * @return an unmodifiable set where the underlying set is sorted
+     */
+    public static <T> Collector<T, SortedSet<T>, Set<T>> toUnmodifiableSortedSet() {
+        return new UnmodifiableSortedSetCollector<>();
+    }
+
+    abstract static class AbstractSortedSetCollector<T, R extends Set<T>> implements Collector<T, SortedSet<T>, R> {
 
         @Override
         public Supplier<SortedSet<T>> supplier() {
@@ -111,7 +148,7 @@ public final class Sets {
 
         @Override
         public BiConsumer<SortedSet<T>, T> accumulator() {
-            return (s, e) -> s.add(e);
+            return SortedSet::add;
         }
 
         @Override
@@ -122,13 +159,21 @@ public final class Sets {
             };
         }
 
+        public abstract Function<SortedSet<T>, R> finisher();
+
+        public abstract Set<Characteristics> characteristics();
+
+    }
+
+    private static class SortedSetCollector<T> extends AbstractSortedSetCollector<T, SortedSet<T>> {
+
         @Override
         public Function<SortedSet<T>, SortedSet<T>> finisher() {
             return Function.identity();
         }
 
         static final Set<Characteristics> CHARACTERISTICS =
-                Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
+            Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH));
 
         @Override
         public Set<Characteristics> characteristics() {
@@ -137,6 +182,20 @@ public final class Sets {
 
     }
 
+    private static class UnmodifiableSortedSetCollector<T> extends AbstractSortedSetCollector<T, Set<T>> {
+
+        @Override
+        public Function<SortedSet<T>, Set<T>> finisher() {
+            return Collections::unmodifiableSet;
+        }
+
+        @Override
+        public Set<Characteristics> characteristics() {
+            return Collections.emptySet();
+        }
+
+    }
+
     public static <T> Set<T> union(Set<T> left, Set<T> right) {
         Objects.requireNonNull(left);
         Objects.requireNonNull(right);

+ 1 - 3
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.HashSet;
 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 class RestGetMappingAction extends BaseRestHandler {
                     }
                 }
 
-                final SortedSet<String> difference = Sets.sortedDifference(Arrays.stream(types).collect(Collectors.toSet()), typeNames);
+                final Set<String> difference = Sets.sortedDifference(Arrays.stream(types).collect(Collectors.toSet()), typeNames);
 
                 // now remove requested aliases that contain wildcards that are simple matches
                 final List<String> matches = new ArrayList<>();

+ 22 - 31
server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java

@@ -42,6 +42,7 @@ import org.elasticsearch.node.Node;
 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.ScheduledExecutorService;
 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 class ThreadPool implements Scheduler, Closeable {
             this.type = type;
         }
 
-        private static final Map<String, ThreadPoolType> TYPE_MAP;
-
-        static {
-            Map<String, ThreadPoolType> typeMap = new HashMap<>();
-            for (ThreadPoolType threadPoolType : ThreadPoolType.values()) {
-                typeMap.put(threadPoolType.getType(), threadPoolType);
-            }
-            TYPE_MAP = Collections.unmodifiableMap(typeMap);
-        }
+        private static final Map<String, ThreadPoolType> 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 class ThreadPool implements Scheduler, Closeable {
         }
     }
 
-    public static final Map<String, ThreadPoolType> THREAD_POOL_TYPES;
-
-    static {
-        HashMap<String, ThreadPoolType> 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<String, ThreadPoolType> 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<String, ExecutorHolder> executors;
 

+ 16 - 1
server/src/test/java/org/elasticsearch/common/util/set/SetsTests.java

@@ -25,6 +25,8 @@ import org.elasticsearch.test.ESTestCase;
 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 class SetsTests extends ESTestCase {
     }
 
     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<Integer>, Set<Integer>, Set<Integer>> sortedDifference,
+        final Consumer<Set<Integer>> asserter) {
         final int endExclusive = randomIntBetween(0, 256);
         final Tuple<Set<Integer>, Set<Integer>> sets = randomSets(endExclusive);
-        final Set<Integer> difference = Sets.sortedDifference(sets.v1(), sets.v2());
+        final Set<Integer> difference = sortedDifference.apply(sets.v1(), sets.v2());
         assertDifference(endExclusive, sets, difference);
         final Iterator<Integer> it = difference.iterator();
         if (it.hasNext()) {
@@ -55,6 +69,7 @@ public class SetsTests extends ESTestCase {
                 current = next;
             }
         }
+        asserter.accept(difference);
     }
 
     public void testIntersection() {

+ 25 - 27
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java

@@ -13,7 +13,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
 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.StringTokenizer;
 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<String, Integer> monthMap = new HashMap<>(20);
-    private static final Map<String, Integer> 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<String, Integer> 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<String, Integer> 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 @@ public class Cron implements ToXContentFragment {
     }
 
     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 @@ public class Cron implements ToXContentFragment {
     }
 
     private int getDayOfWeekNumber(String s) {
-        Integer integer = dayMap.get(s);
+        Integer integer = DAY_MAP.get(s);
 
         if (integer == null) {
             return -1;

+ 4 - 10
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/persistence/DatafeedConfigProvider.java

@@ -45,20 +45,18 @@ import org.elasticsearch.index.query.WildcardQueryBuilder;
 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<String, String> TO_XCONTENT_PARAMS;
-    static {
-        Map<String, String> 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<String, String> TO_XCONTENT_PARAMS = Map.of(
+        ToXContentParams.FOR_INTERNAL_STORAGE, "true",
+        ToXContentParams.INCLUDE_TYPE, "true");
 
     public DatafeedConfigProvider(Client client, NamedXContentRegistry xContentRegistry) {
         this.client = client;

+ 1 - 10
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeController.java

@@ -17,8 +17,6 @@ import java.io.IOException;
 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<String, Object> UNKNOWN_NATIVE_CODE_INFO;
-
-    static {
-        Map<String, Object> 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<String, Object> UNKNOWN_NATIVE_CODE_INFO = Map.of("version", "N/A", "build_hash", "N/A");
 
     private final CppLogMessageHandler cppLogHandler;
     private final OutputStream commandStream;

+ 57 - 63
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/DomainSplitFunction.java

@@ -9,16 +9,18 @@ import org.apache.logging.log4j.LogManager;
 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<String, String> exact;
-    private static final Map<String, String> under;
-    private static final Map<String, String> excluded;
-    static {
-        Map<String, String> exactMap = new HashMap<>(2048);
-
-        String exactResourceName = "org/elasticsearch/xpack/ml/transforms/exact.properties";
+    private static final Map<String, String> 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<String, String> 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<String> 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<String, String> 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<String, String> 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() {}

+ 29 - 33
x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTestCase.java

@@ -21,13 +21,13 @@ import org.junit.Before;
 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<String> 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<String> 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 abstract class KerberosTestCase extends ESTestCase {
     }
 
     private static boolean isLocaleUnsupported() {
-        return unsupportedLocaleLanguages.contains(Locale.getDefault().getLanguage());
+        return UNSUPPORTED_LOCALE_LANGUAGES.contains(Locale.getDefault().getLanguage());
     }
 
     @Before