From be632fb86a157a1ad3fd1f10ffacf23444e029b5 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Sun, 21 Apr 2019 12:59:19 -0400 Subject: [PATCH 01/20] Use Java 11 collections conveniences everywhere This commit replaces all applicable uses with Java 11 collections convenience methods. --- .../ml/filestructurefinder/FileStructure.java | 11 +- .../security/GetPrivilegesResponse.java | 3 +- .../client/security/GetUsersResponse.java | 10 +- .../CompositeRoleMapperExpression.java | 4 +- .../fields/FieldRoleMapperExpression.java | 4 +- .../client/security/user/User.java | 10 +- .../privileges/AbstractIndicesPrivileges.java | 9 +- .../user/privileges/ApplicationPrivilege.java | 6 +- .../ApplicationResourcePrivileges.java | 6 +- .../user/privileges/GlobalPrivileges.java | 3 +- .../privileges/UserIndicesPrivileges.java | 5 +- .../client/PreBuiltTransportClient.java | 11 +- .../ConstructingObjectParserTests.java | 6 +- .../ingest/common/IngestCommonPlugin.java | 61 +- .../ingest/common/ScriptProcessor.java | 9 +- .../common/ScriptProcessorFactoryTests.java | 12 +- .../mustache/CustomMustacheFactory.java | 16 +- .../org/elasticsearch/painless/Locals.java | 6 +- .../action/PainlessExecuteAction.java | 11 +- .../plugin/store/smb/SMBStorePlugin.java | 7 +- .../node/tasks/list/ListTasksResponse.java | 2 +- .../cluster/node/tasks/list/TaskGroup.java | 4 +- .../cluster/remote/RemoteInfoResponse.java | 6 +- .../rollover/TransportRolloverAction.java | 21 +- .../support/tasks/BaseTasksResponse.java | 4 +- .../bootstrap/SystemCallFilter.java | 9 +- .../TransportClientNodesService.java | 8 +- .../elasticsearch/cluster/DiffableUtils.java | 5 +- .../cluster/block/ClusterBlocks.java | 4 +- .../coordination/CoordinationMetaData.java | 4 +- .../cluster/metadata/IndexMetaData.java | 2 +- .../metadata/IndexNameExpressionResolver.java | 8 +- .../metadata/RepositoriesMetaData.java | 3 +- .../routing/IndexShardRoutingTable.java | 2 +- .../routing/allocation/RoutingAllocation.java | 3 +- .../common/collect/MapBuilder.java | 5 +- .../inject/internal/BindingBuilder.java | 6 +- .../inject/internal/InstanceBindingImpl.java | 5 +- .../internal/ProviderInstanceBindingImpl.java | 5 +- .../common/io/stream/StreamOutput.java | 84 +-- .../common/lucene/ShardCoreKeyMap.java | 2 +- .../settings/AbstractScopedSettings.java | 2 +- .../common/settings/ClusterSettings.java | 562 +++++++++--------- .../common/settings/IndexScopedSettings.java | 245 ++++---- .../common/settings/Setting.java | 3 +- .../common/settings/Settings.java | 3 +- .../common/settings/SettingsFilter.java | 4 +- .../elasticsearch/common/time/DateUtils.java | 235 ++++---- .../common/util/concurrent/ThreadContext.java | 3 +- .../elasticsearch/env/NodeEnvironment.java | 4 +- .../gateway/AsyncShardFetch.java | 3 +- .../gateway/DanglingIndicesState.java | 3 +- .../index/CompositeIndexEventListener.java | 4 +- .../index/analysis/Analysis.java | 76 ++- .../plain/PagedBytesAtomicFieldData.java | 11 +- .../index/mapper/DocumentMapperParser.java | 4 +- .../index/query/QueryShardContext.java | 4 +- .../index/similarity/SimilarityProviders.java | 76 +-- .../flush/ShardsSyncedFlushResult.java | 3 +- .../indices/recovery/RecoveryState.java | 4 +- .../ingest/ConditionalProcessor.java | 22 +- .../admin/cluster/RestNodesStatsAction.java | 34 +- .../rest/action/cat/AbstractCatAction.java | 6 +- .../script/AbstractSortScript.java | 25 +- .../script/AggregationScript.java | 27 +- .../elasticsearch/script/ClassPermission.java | 34 +- .../org/elasticsearch/script/FieldScript.java | 18 +- .../org/elasticsearch/script/ScoreScript.java | 20 +- .../script/ScriptedMetricAggContexts.java | 28 +- .../script/TermsSetQueryScript.java | 27 +- .../elasticsearch/script/UpdateScript.java | 13 +- .../DateHistogramAggregationBuilder.java | 42 +- .../search/lookup/LeafSearchLookup.java | 24 +- .../search/sort/SortBuilder.java | 18 +- .../transport/RemoteClusterConnection.java | 2 +- .../transport/TransportService.java | 22 +- .../tasks/RecordingTaskManagerListener.java | 2 +- .../cluster/node/tasks/TestTaskPlugin.java | 8 +- .../node/tasks/TransportTasksActionTests.java | 2 +- .../reroute/ClusterRerouteRequestTests.java | 28 +- .../shrink/TransportResizeActionTests.java | 4 +- ...icsearchUncaughtExceptionHandlerTests.java | 26 +- .../MetaDataCreateIndexServiceTests.java | 8 +- .../structure/RoutingIteratorTests.java | 5 +- .../index/mapper/ExternalMapperPlugin.java | 20 +- .../elasticsearch/index/store/StoreTests.java | 5 +- .../PersistentTasksClusterServiceTests.java | 11 +- .../persistent/TestPersistentTasksPlugin.java | 3 +- .../aggregations/AggregationsTests.java | 224 ++++--- .../SharedClusterSnapshotRestoreIT.java | 20 +- .../elasticsearch/test/ESIntegTestCase.java | 6 +- .../test/rest/yaml/Features.java | 11 +- .../rest/yaml/section/ExecutableSection.java | 7 +- .../xpack/ccr/action/ShardFollowNodeTask.java | 5 + .../xpack/ccr/action/ShardFollowTask.java | 4 +- .../action/TransportResumeFollowAction.java | 174 +++--- .../action/TransportXPackUsageAction.java | 2 +- .../GetDataFrameTransformsStatsAction.java | 3 +- .../ml/filestructurefinder/FileStructure.java | 11 +- .../privilege/DeletePrivilegesResponse.java | 3 +- .../privilege/PutPrivilegesRequest.java | 3 +- .../oidc/OpenIdConnectRealmSettings.java | 6 +- .../permission/ApplicationPermission.java | 3 +- .../xpack/core/ssl/SSLService.java | 4 +- .../support/xcontent/WatcherParams.java | 3 +- .../DeprecationInfoActionResponseTests.java | 15 +- .../xpack/deprecation/Deprecation.java | 9 +- .../xpack/deprecation/DeprecationChecks.java | 14 +- .../xpack/ml/MachineLearning.java | 24 +- .../FileStructureFinderManager.java | 270 +++++++-- .../FileStructureOverrides.java | 4 +- .../ml/job/persistence/JobConfigProvider.java | 8 +- .../ml/utils/TypedChainTaskExecutor.java | 6 +- .../xpack/monitoring/Monitoring.java | 2 +- .../rest/action/RestMonitoringBulkAction.java | 11 +- .../rollup/rest/RestRollupSearchAction.java | 7 +- .../xpack/security/Security.java | 36 +- .../xpack/security/authc/InternalRealms.java | 47 +- .../kerberos/KerberosTicketValidator.java | 42 +- .../ldap/UserAttributeGroupsResolver.java | 2 +- .../security/authc/support/DnRoleMapper.java | 33 +- .../authc/support/UserRoleMapper.java | 3 +- .../authz/store/CompositeRolesStore.java | 2 +- .../xpack/sql/querydsl/query/MatchQuery.java | 28 +- .../sql/querydsl/query/MultiMatchQuery.java | 39 +- .../sql/querydsl/query/QueryStringQuery.java | 58 +- .../elasticsearch/xpack/watcher/Watcher.java | 26 +- .../common/http/HttpRequestTemplate.java | 5 +- .../watcher/test/WatcherMockScriptPlugin.java | 52 +- .../xpack/watcher/watch/WatchTests.java | 10 +- .../security/authc/kerberos/SpnegoClient.java | 40 +- 131 files changed, 1640 insertions(+), 1777 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ml/filestructurefinder/FileStructure.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ml/filestructurefinder/FileStructure.java index 215c19a0b3b78..9e3e2162a69bc 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ml/filestructurefinder/FileStructure.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/ml/filestructurefinder/FileStructure.java @@ -25,7 +25,6 @@ import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; -import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -148,22 +147,20 @@ private FileStructure(int numLinesAnalyzed, int numMessagesAnalyzed, String samp this.format = Objects.requireNonNull(format); this.multilineStartPattern = multilineStartPattern; this.excludeLinesPattern = excludeLinesPattern; - this.columnNames = (columnNames == null) ? null : Collections.unmodifiableList(new ArrayList<>(columnNames)); + this.columnNames = (columnNames == null) ? null : List.copyOf(columnNames); this.hasHeaderRow = hasHeaderRow; this.delimiter = delimiter; this.quote = quote; this.shouldTrimFields = shouldTrimFields; this.grokPattern = grokPattern; this.timestampField = timestampField; - this.jodaTimestampFormats = - (jodaTimestampFormats == null) ? null : Collections.unmodifiableList(new ArrayList<>(jodaTimestampFormats)); - this.javaTimestampFormats = - (javaTimestampFormats == null) ? null : Collections.unmodifiableList(new ArrayList<>(javaTimestampFormats)); + this.jodaTimestampFormats = (jodaTimestampFormats == null) ? null : List.copyOf(jodaTimestampFormats); + this.javaTimestampFormats = (javaTimestampFormats == null) ? null : List.copyOf(javaTimestampFormats); this.needClientTimezone = needClientTimezone; this.mappings = Collections.unmodifiableSortedMap(new TreeMap<>(mappings)); this.ingestPipeline = (ingestPipeline == null) ? null : Collections.unmodifiableMap(new LinkedHashMap<>(ingestPipeline)); this.fieldStats = Collections.unmodifiableSortedMap(new TreeMap<>(fieldStats)); - this.explanation = (explanation == null) ? null : Collections.unmodifiableList(new ArrayList<>(explanation)); + this.explanation = (explanation == null) ? null : List.copyOf(explanation); } public int getNumLinesAnalyzed() { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetPrivilegesResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetPrivilegesResponse.java index 182f14ef00c51..168ca17c926c5 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetPrivilegesResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetPrivilegesResponse.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -44,7 +43,7 @@ public Set getPrivileges() { } public GetPrivilegesResponse(Collection privileges) { - this.privileges = Collections.unmodifiableSet(new HashSet<>(privileges)); + this.privileges = Set.copyOf(privileges); } public static GetPrivilegesResponse fromXContent(XContentParser parser) throws IOException { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java index 39d4a25a64207..abb37f28306f0 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java @@ -122,11 +122,11 @@ protected static final class ParsedUser { public ParsedUser(String username, Collection roles, Map metadata, Boolean enabled, @Nullable String fullName, @Nullable String email) { - String checkedUsername = username = Objects.requireNonNull(username, "`username` is required, cannot be null"); - Collection checkedRoles = Collections.unmodifiableSet(new HashSet<>( - Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead."))); - Map checkedMetadata = Collections - .unmodifiableMap(Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); + String checkedUsername = Objects.requireNonNull(username, "`username` is required, cannot be null"); + Collection checkedRoles = + Set.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); + Map checkedMetadata = Collections.unmodifiableMap( + Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); this.user = new User(checkedUsername, checkedRoles, checkedMetadata, fullName, email); this.enabled = enabled; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/expressions/CompositeRoleMapperExpression.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/expressions/CompositeRoleMapperExpression.java index 3373f325bfcdb..b44abab37ec71 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/expressions/CompositeRoleMapperExpression.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/expressions/CompositeRoleMapperExpression.java @@ -23,8 +23,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -53,7 +51,7 @@ public abstract class CompositeRoleMapperExpression implements RoleMapperExpress assert name != null : "field name cannot be null"; assert elements != null : "at least one field expression is required"; this.name = name; - this.elements = Collections.unmodifiableList(Arrays.asList(elements)); + this.elements = List.of(elements); } public String getName() { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/fields/FieldRoleMapperExpression.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/fields/FieldRoleMapperExpression.java index 4111b9fa2a2c3..1a6bded342191 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/fields/FieldRoleMapperExpression.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/fields/FieldRoleMapperExpression.java @@ -23,8 +23,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -53,7 +51,7 @@ public FieldRoleMapperExpression(final String field, final Object... values) { throw new IllegalArgumentException("null or empty values for field (" + field + ")"); } this.field = field; - this.values = Collections.unmodifiableList(Arrays.asList(values)); + this.values = List.of(values); } public String getField() { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java index 4ac8f54c4741b..7353b7f350cbf 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java @@ -24,7 +24,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -52,11 +51,10 @@ public final class User { */ public User(String username, Collection roles, Map metadata, @Nullable String fullName, @Nullable String email) { - this.username = username = Objects.requireNonNull(username, "`username` is required, cannot be null"); - this.roles = Collections.unmodifiableSet(new HashSet<>( - Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead."))); - this.metadata = Collections - .unmodifiableMap(Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); + this.username = Objects.requireNonNull(username, "`username` is required, cannot be null"); + this.roles = Set.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); + this.metadata = Collections.unmodifiableMap( + Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); this.fullName = fullName; this.email = email; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java index 4187ca7638d4e..8c16e530c524c 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java @@ -31,7 +31,6 @@ import java.io.UncheckedIOException; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Objects; import java.util.Set; @@ -55,8 +54,8 @@ public abstract class AbstractIndicesPrivileges { if (null == privileges || privileges.isEmpty()) { throw new IllegalArgumentException("indices privileges must define at least one privilege"); } - this.indices = Collections.unmodifiableSet(new HashSet<>(indices)); - this.privileges = Collections.unmodifiableSet(new HashSet<>(privileges)); + this.indices = Set.copyOf(indices); + this.privileges = Set.copyOf(privileges); this.allowRestrictedIndices = allowRestrictedIndices; } @@ -127,9 +126,9 @@ static FieldSecurity parse(XContentParser parser, Void context) throws IOExcepti FieldSecurity(Collection grantedFields, Collection deniedFields) { // unspecified granted fields means no restriction - this.grantedFields = grantedFields == null ? null : Collections.unmodifiableSet(new HashSet<>(grantedFields)); + this.grantedFields = grantedFields == null ? null : Set.copyOf(grantedFields); // unspecified denied fields means no restriction - this.deniedFields = deniedFields == null ? null : Collections.unmodifiableSet(new HashSet<>(deniedFields)); + this.deniedFields = deniedFields == null ? null : Set.copyOf(deniedFields); } /** diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java index fc21dfc0b2816..6b8da58f13223 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java @@ -29,11 +29,9 @@ import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; - import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -72,12 +70,12 @@ public ApplicationPrivilege(String application, String name, Collection if (actions == null || actions.isEmpty()) { throw new IllegalArgumentException("actions must be provided"); } else { - this.actions = Collections.unmodifiableSet(new HashSet<>(actions)); + this.actions = Set.copyOf(actions); } if (metadata == null || metadata.isEmpty()) { this.metadata = Collections.emptyMap(); } else { - this.metadata = Collections.unmodifiableMap(metadata); + this.metadata = Map.copyOf(metadata); } } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java index 8846e259e26b3..6dcb049f33e48 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java @@ -30,8 +30,6 @@ import java.io.IOException; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.Objects; import java.util.Set; @@ -96,8 +94,8 @@ public ApplicationResourcePrivileges(String application, Collection priv throw new IllegalArgumentException("application privileges must refer to at least one resource"); } this.application = application; - this.privileges = Collections.unmodifiableSet(new HashSet<>(privileges)); - this.resources = Collections.unmodifiableSet(new HashSet<>(resources)); + this.privileges = Set.copyOf(privileges); + this.resources = Set.copyOf(resources); } public String getApplication() { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/GlobalPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/GlobalPrivileges.java index c1bd5550eca1a..81768e894b6ce 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/GlobalPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/GlobalPrivileges.java @@ -28,7 +28,6 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -82,7 +81,7 @@ public GlobalPrivileges(Collection privilege throw new IllegalArgumentException("Privileges cannot be empty or null"); } // duplicates are just ignored - this.privileges = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull(privileges))); + this.privileges = Set.copyOf(Objects.requireNonNull(privileges)); this.privilegesByCategoryMap = Collections .unmodifiableMap(this.privileges.stream().collect(Collectors.groupingBy(GlobalOperationPrivilege::getCategory))); for (final Map.Entry> privilegesByCategory : privilegesByCategoryMap.entrySet()) { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java index 9878bb0071740..48a63dabfc3c1 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; @@ -75,8 +74,8 @@ public static UserIndicesPrivileges fromXContent(XContentParser parser) throws I public UserIndicesPrivileges(Collection indices, Collection privileges, boolean allowRestrictedIndices, Collection fieldSecurity, Collection query) { super(indices, privileges, allowRestrictedIndices); - this.fieldSecurity = fieldSecurity == null ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(fieldSecurity)); - this.query = query == null ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(query)); + this.fieldSecurity = fieldSecurity == null ? Collections.emptySet() : Set.copyOf(fieldSecurity); + this.query = query == null ? Collections.emptySet() : Set.copyOf(query); } public Set getFieldSecurity() { diff --git a/client/transport/src/main/java/org/elasticsearch/transport/client/PreBuiltTransportClient.java b/client/transport/src/main/java/org/elasticsearch/transport/client/PreBuiltTransportClient.java index 7bde7fbc06f6b..4a78c38d06cc6 100644 --- a/client/transport/src/main/java/org/elasticsearch/transport/client/PreBuiltTransportClient.java +++ b/client/transport/src/main/java/org/elasticsearch/transport/client/PreBuiltTransportClient.java @@ -21,7 +21,6 @@ import io.netty.util.ThreadDeathWatcher; import io.netty.util.concurrent.GlobalEventExecutor; - import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.network.NetworkModule; @@ -35,7 +34,7 @@ import java.util.Arrays; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.concurrent.TimeUnit; /** @@ -87,13 +86,7 @@ private static void setSystemPropertyIfUnset(final String key, final String valu } private static final Collection> PRE_INSTALLED_PLUGINS = - Collections.unmodifiableList( - Arrays.asList( - Netty4Plugin.class, - ReindexPlugin.class, - PercolatorPlugin.class, - MustachePlugin.class, - ParentJoinPlugin.class)); + List.of(Netty4Plugin.class, ReindexPlugin.class, PercolatorPlugin.class, MustachePlugin.class, ParentJoinPlugin.class); /** * Creates a new transport client with pre-installed plugins. diff --git a/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java b/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java index 5fc3e612c18f7..00e34183d2f78 100644 --- a/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java +++ b/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java @@ -29,10 +29,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.Arrays; import java.util.List; -import static java.util.Collections.unmodifiableList; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; import static org.hamcrest.Matchers.anyOf; @@ -378,8 +376,8 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws public static final ConstructingObjectParser PARSER_VEGETABLE_OPTIONAL = buildParser(true, false); public static final ConstructingObjectParser PARSER_ALL_OPTIONAL = buildParser(false, false); - public static final List> ALL_PARSERS = unmodifiableList( - Arrays.asList(PARSER, PARSER_VEGETABLE_OPTIONAL, PARSER_ALL_OPTIONAL)); + public static final List> ALL_PARSERS = + List.of(PARSER, PARSER_VEGETABLE_OPTIONAL, PARSER_ALL_OPTIONAL); public static final ConstructingObjectParser PARSER_INT_CONTEXT = buildContextParser(); diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/IngestCommonPlugin.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/IngestCommonPlugin.java index a839e147c77ad..c3b1328d0b276 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/IngestCommonPlugin.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/IngestCommonPlugin.java @@ -42,11 +42,12 @@ import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; +import static java.util.Map.entry; + public class IngestCommonPlugin extends Plugin implements ActionPlugin, IngestPlugin { static final Map GROK_PATTERNS = Grok.getBuiltinPatterns(); @@ -60,39 +61,39 @@ public IngestCommonPlugin() { @Override public Map getProcessors(Processor.Parameters parameters) { - Map processors = new HashMap<>(); - processors.put(DateProcessor.TYPE, new DateProcessor.Factory(parameters.scriptService)); - processors.put(SetProcessor.TYPE, new SetProcessor.Factory(parameters.scriptService)); - processors.put(AppendProcessor.TYPE, new AppendProcessor.Factory(parameters.scriptService)); - processors.put(RenameProcessor.TYPE, new RenameProcessor.Factory(parameters.scriptService)); - processors.put(RemoveProcessor.TYPE, new RemoveProcessor.Factory(parameters.scriptService)); - processors.put(SplitProcessor.TYPE, new SplitProcessor.Factory()); - processors.put(JoinProcessor.TYPE, new JoinProcessor.Factory()); - processors.put(UppercaseProcessor.TYPE, new UppercaseProcessor.Factory()); - processors.put(LowercaseProcessor.TYPE, new LowercaseProcessor.Factory()); - processors.put(TrimProcessor.TYPE, new TrimProcessor.Factory()); - processors.put(ConvertProcessor.TYPE, new ConvertProcessor.Factory()); - processors.put(GsubProcessor.TYPE, new GsubProcessor.Factory()); - processors.put(FailProcessor.TYPE, new FailProcessor.Factory(parameters.scriptService)); - processors.put(ForEachProcessor.TYPE, new ForEachProcessor.Factory(parameters.scriptService)); - processors.put(DateIndexNameProcessor.TYPE, new DateIndexNameProcessor.Factory(parameters.scriptService)); - processors.put(SortProcessor.TYPE, new SortProcessor.Factory()); - processors.put(GrokProcessor.TYPE, new GrokProcessor.Factory(GROK_PATTERNS, createGrokThreadWatchdog(parameters))); - processors.put(ScriptProcessor.TYPE, new ScriptProcessor.Factory(parameters.scriptService)); - processors.put(DotExpanderProcessor.TYPE, new DotExpanderProcessor.Factory()); - processors.put(JsonProcessor.TYPE, new JsonProcessor.Factory()); - processors.put(KeyValueProcessor.TYPE, new KeyValueProcessor.Factory()); - processors.put(URLDecodeProcessor.TYPE, new URLDecodeProcessor.Factory()); - processors.put(BytesProcessor.TYPE, new BytesProcessor.Factory()); - processors.put(PipelineProcessor.TYPE, new PipelineProcessor.Factory(parameters.ingestService)); - processors.put(DissectProcessor.TYPE, new DissectProcessor.Factory()); - processors.put(DropProcessor.TYPE, new DropProcessor.Factory()); - return Collections.unmodifiableMap(processors); + return Map.ofEntries( + entry(DateProcessor.TYPE, new DateProcessor.Factory(parameters.scriptService)), + entry(SetProcessor.TYPE, new SetProcessor.Factory(parameters.scriptService)), + entry(AppendProcessor.TYPE, new AppendProcessor.Factory(parameters.scriptService)), + entry(RenameProcessor.TYPE, new RenameProcessor.Factory(parameters.scriptService)), + entry(RemoveProcessor.TYPE, new RemoveProcessor.Factory(parameters.scriptService)), + entry(SplitProcessor.TYPE, new SplitProcessor.Factory()), + entry(JoinProcessor.TYPE, new JoinProcessor.Factory()), + entry(UppercaseProcessor.TYPE, new UppercaseProcessor.Factory()), + entry(LowercaseProcessor.TYPE, new LowercaseProcessor.Factory()), + entry(TrimProcessor.TYPE, new TrimProcessor.Factory()), + entry(ConvertProcessor.TYPE, new ConvertProcessor.Factory()), + entry(GsubProcessor.TYPE, new GsubProcessor.Factory()), + entry(FailProcessor.TYPE, new FailProcessor.Factory(parameters.scriptService)), + entry(ForEachProcessor.TYPE, new ForEachProcessor.Factory(parameters.scriptService)), + entry(DateIndexNameProcessor.TYPE, new DateIndexNameProcessor.Factory(parameters.scriptService)), + entry(SortProcessor.TYPE, new SortProcessor.Factory()), + entry(GrokProcessor.TYPE, new GrokProcessor.Factory(GROK_PATTERNS, createGrokThreadWatchdog(parameters))), + entry(ScriptProcessor.TYPE, new ScriptProcessor.Factory(parameters.scriptService)), + entry(DotExpanderProcessor.TYPE, new DotExpanderProcessor.Factory()), + entry(JsonProcessor.TYPE, new JsonProcessor.Factory()), + entry(KeyValueProcessor.TYPE, new KeyValueProcessor.Factory()), + entry(URLDecodeProcessor.TYPE, new URLDecodeProcessor.Factory()), + entry(BytesProcessor.TYPE, new BytesProcessor.Factory()), + entry(PipelineProcessor.TYPE, new PipelineProcessor.Factory(parameters.ingestService)), + entry(DissectProcessor.TYPE, new DissectProcessor.Factory()), + entry(DropProcessor.TYPE, new DropProcessor.Factory())); } @Override public List> getActions() { - return Arrays.asList(new ActionHandler<>(GrokProcessorGetAction.INSTANCE, GrokProcessorGetAction.TransportAction.class)); + return Collections.singletonList( + new ActionHandler<>(GrokProcessorGetAction.INSTANCE, GrokProcessorGetAction.TransportAction.class)); } @Override diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java index fcc6c68014207..4bbd701ff32e2 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java @@ -38,8 +38,6 @@ import java.io.InputStream; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import static org.elasticsearch.ingest.ConfigurationUtils.newConfigurationException; @@ -51,12 +49,7 @@ public final class ScriptProcessor extends AbstractProcessor { private static final Map DEPRECATIONS; static { - Map deprecations = new HashMap<>(); - deprecations.put( - "_type", - "[types removal] Looking up doc types [_type] in scripts is deprecated." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); + DEPRECATIONS = Map.of("_type", "[types removal] Looking up doc types [_type] in scripts is deprecated."); } public static final String TYPE = "script"; diff --git a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java index d7f8e8838bb8c..d35ca5946e009 100644 --- a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java +++ b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java @@ -41,13 +41,7 @@ public class ScriptProcessorFactoryTests extends ESTestCase { private ScriptProcessor.Factory factory; - private static final Map ingestScriptParamToType; - static { - Map map = new HashMap<>(); - map.put("id", "stored"); - map.put("source", "inline"); - ingestScriptParamToType = Collections.unmodifiableMap(map); - } + private static final Map INGEST_SCRIPT_PARAM_TO_TYPE = Map.of("id", "stored", "source", "inline"); @Before public void init() { @@ -60,7 +54,7 @@ public void testFactoryValidationWithDefaultLang() throws Exception { configMap.put(randomType, "foo"); ScriptProcessor processor = factory.create(null, randomAlphaOfLength(10), configMap); assertThat(processor.getScript().getLang(), equalTo(randomType.equals("id") ? null : Script.DEFAULT_SCRIPT_LANG)); - assertThat(processor.getScript().getType().toString(), equalTo(ingestScriptParamToType.get(randomType))); + assertThat(processor.getScript().getType().toString(), equalTo(INGEST_SCRIPT_PARAM_TO_TYPE.get(randomType))); assertThat(processor.getScript().getParams(), equalTo(Collections.emptyMap())); } @@ -72,7 +66,7 @@ public void testFactoryValidationWithParams() throws Exception { configMap.put("params", randomParams); ScriptProcessor processor = factory.create(null, randomAlphaOfLength(10), configMap); assertThat(processor.getScript().getLang(), equalTo(randomType.equals("id") ? null : Script.DEFAULT_SCRIPT_LANG)); - assertThat(processor.getScript().getType().toString(), equalTo(ingestScriptParamToType.get(randomType))); + assertThat(processor.getScript().getType().toString(), equalTo(INGEST_SCRIPT_PARAM_TO_TYPE.get(randomType))); assertThat(processor.getScript().getParams(), equalTo(randomParams)); } diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java index 04835bed116d4..a398491121edd 100644 --- a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java +++ b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java @@ -30,7 +30,6 @@ import com.github.mustachejava.codes.DefaultMustache; import com.github.mustachejava.codes.IterableCode; import com.github.mustachejava.codes.WriteCode; - import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; @@ -41,7 +40,6 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -60,15 +58,11 @@ public class CustomMustacheFactory extends DefaultMustacheFactory { private static final String DEFAULT_MIME_TYPE = JSON_MIME_TYPE; - private static final Map> ENCODERS; - static { - Map> encoders = new HashMap<>(); - encoders.put(JSON_MIME_TYPE_WITH_CHARSET, JsonEscapeEncoder::new); - encoders.put(JSON_MIME_TYPE, JsonEscapeEncoder::new); - encoders.put(PLAIN_TEXT_MIME_TYPE, DefaultEncoder::new); - encoders.put(X_WWW_FORM_URLENCODED_MIME_TYPE, UrlEncoder::new); - ENCODERS = Collections.unmodifiableMap(encoders); - } + private static final Map> ENCODERS = Map.of( + JSON_MIME_TYPE_WITH_CHARSET, JsonEscapeEncoder::new, + JSON_MIME_TYPE, JsonEscapeEncoder::new, + PLAIN_TEXT_MIME_TYPE, DefaultEncoder::new, + X_WWW_FORM_URLENCODED_MIME_TYPE, UrlEncoder::new); private final Encoder encoder; diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java index 85cdfa9f915b4..121111f8c317c 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java @@ -24,11 +24,9 @@ import org.elasticsearch.painless.lookup.PainlessLookupUtility; import java.lang.invoke.MethodType; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -71,9 +69,7 @@ public LocalMethod(String name, Class returnType, List> typeParamete public static final String THIS = "#this"; /** Set of reserved keywords. */ - public static final Set KEYWORDS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - THIS, LOOP - ))); + public static final Set KEYWORDS = Set.of(THIS, LOOP); /** Creates a new local variable scope (e.g. loop) inside the current scope */ public static Locals newLocalScope(Locals currentScope) { diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java index e8d93b8ef772e..e4a10d3f74478 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java @@ -83,8 +83,6 @@ import org.elasticsearch.transport.TransportService; import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -123,11 +121,10 @@ public static class Request extends SingleShardRequest implements ToXCo static final Map> SUPPORTED_CONTEXTS; static { - Map> supportedContexts = new HashMap<>(); - supportedContexts.put("painless_test", PainlessTestScript.CONTEXT); - supportedContexts.put("filter", FilterScript.CONTEXT); - supportedContexts.put("score", ScoreScript.CONTEXT); - SUPPORTED_CONTEXTS = Collections.unmodifiableMap(supportedContexts); + SUPPORTED_CONTEXTS = Map.of( + "painless_test", PainlessTestScript.CONTEXT, + "filter", FilterScript.CONTEXT, + "score", ScoreScript.CONTEXT); } static ScriptContext fromScriptContextName(String name) { diff --git a/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java b/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java index a2b0f46345231..4093368228258 100644 --- a/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java +++ b/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java @@ -26,8 +26,6 @@ import org.elasticsearch.plugins.IndexStorePlugin; import org.elasticsearch.plugins.Plugin; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.function.Function; @@ -35,10 +33,7 @@ public class SMBStorePlugin extends Plugin implements IndexStorePlugin { @Override public Map> getIndexStoreFactories() { - final Map> indexStoreFactories = new HashMap<>(2); - indexStoreFactories.put("smb_mmap_fs", SmbMmapFsIndexStore::new); - indexStoreFactories.put("smb_simple_fs", SmbSimpleFsIndexStore::new); - return Collections.unmodifiableMap(indexStoreFactories); + return Map.of("smb_mmap_fs", SmbMmapFsIndexStore::new, "smb_simple_fs", SmbSimpleFsIndexStore::new); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java index 166a59f235902..557338ed0f77e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java @@ -61,7 +61,7 @@ public class ListTasksResponse extends BaseTasksResponse implements ToXContentOb public ListTasksResponse(List tasks, List taskFailures, List nodeFailures) { super(taskFailures, nodeFailures); - this.tasks = tasks == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(tasks)); + this.tasks = tasks == null ? Collections.emptyList() : List.copyOf(tasks); } public ListTasksResponse(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/TaskGroup.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/TaskGroup.java index c0a0930aaaf34..78ffadd791e63 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/TaskGroup.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/list/TaskGroup.java @@ -19,14 +19,12 @@ package org.elasticsearch.action.admin.cluster.node.tasks.list; -import org.elasticsearch.common.xcontent.ToXContent.Params; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.tasks.TaskInfo; import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -42,7 +40,7 @@ public class TaskGroup implements ToXContentObject { public TaskGroup(TaskInfo task, List childTasks) { this.task = task; - this.childTasks = Collections.unmodifiableList(new ArrayList<>(childTasks)); + this.childTasks = List.copyOf(childTasks); } public static Builder builder(TaskInfo taskInfo) { diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/remote/RemoteInfoResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/remote/RemoteInfoResponse.java index b8c2c29a0c8f9..fbb94069342b8 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/remote/RemoteInfoResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/remote/RemoteInfoResponse.java @@ -20,16 +20,14 @@ package org.elasticsearch.action.admin.cluster.remote; import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.transport.RemoteConnectionInfo; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.transport.RemoteConnectionInfo; import java.io.IOException; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; public final class RemoteInfoResponse extends ActionResponse implements ToXContentObject { @@ -40,7 +38,7 @@ public final class RemoteInfoResponse extends ActionResponse implements ToXConte } RemoteInfoResponse(Collection infos) { - this.infos = Collections.unmodifiableList(new ArrayList<>(infos)); + this.infos = List.copyOf(infos); } public List getInfos() { diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverAction.java b/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverAction.java index edd59f8b18ca1..c36d6092a7e49 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverAction.java @@ -50,7 +50,6 @@ import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Locale; @@ -58,8 +57,6 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import static java.util.Collections.unmodifiableList; - /** * Main class to swap the index pointed to by an alias, given some conditions */ @@ -200,24 +197,22 @@ public void onFailure(Exception e) { static IndicesAliasesClusterStateUpdateRequest prepareRolloverAliasesUpdateRequest(String oldIndex, String newIndex, RolloverRequest request) { - List actions = unmodifiableList(Arrays.asList( - new AliasAction.Add(newIndex, request.getAlias(), null, null, null, null), - new AliasAction.Remove(oldIndex, request.getAlias()))); - final IndicesAliasesClusterStateUpdateRequest updateRequest = new IndicesAliasesClusterStateUpdateRequest(actions) + final List actions = List.of( + new AliasAction.Add(newIndex, request.getAlias(), null, null, null, null), + new AliasAction.Remove(oldIndex, request.getAlias())); + return new IndicesAliasesClusterStateUpdateRequest(actions) .ackTimeout(request.ackTimeout()) .masterNodeTimeout(request.masterNodeTimeout()); - return updateRequest; } static IndicesAliasesClusterStateUpdateRequest prepareRolloverAliasesWriteIndexUpdateRequest(String oldIndex, String newIndex, RolloverRequest request) { - List actions = unmodifiableList(Arrays.asList( - new AliasAction.Add(newIndex, request.getAlias(), null, null, null, true), - new AliasAction.Add(oldIndex, request.getAlias(), null, null, null, false))); - final IndicesAliasesClusterStateUpdateRequest updateRequest = new IndicesAliasesClusterStateUpdateRequest(actions) + final List actions = List.of( + new AliasAction.Add(newIndex, request.getAlias(), null, null, null, true), + new AliasAction.Add(oldIndex, request.getAlias(), null, null, null, false)); + return new IndicesAliasesClusterStateUpdateRequest(actions) .ackTimeout(request.ackTimeout()) .masterNodeTimeout(request.masterNodeTimeout()); - return updateRequest; } diff --git a/server/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksResponse.java b/server/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksResponse.java index d859959f2e661..8c1980bae8af7 100644 --- a/server/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksResponse.java +++ b/server/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksResponse.java @@ -51,8 +51,8 @@ public class BaseTasksResponse extends ActionResponse { private List nodeFailures; public BaseTasksResponse(List taskFailures, List nodeFailures) { - this.taskFailures = taskFailures == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(taskFailures)); - this.nodeFailures = nodeFailures == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(nodeFailures)); + this.taskFailures = taskFailures == null ? Collections.emptyList() : List.copyOf(taskFailures); + this.nodeFailures = nodeFailures == null ? Collections.emptyList() : List.copyOf(nodeFailures); } public BaseTasksResponse(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/bootstrap/SystemCallFilter.java b/server/src/main/java/org/elasticsearch/bootstrap/SystemCallFilter.java index 59f8bd5daf77b..f1536fe944e7f 100644 --- a/server/src/main/java/org/elasticsearch/bootstrap/SystemCallFilter.java +++ b/server/src/main/java/org/elasticsearch/bootstrap/SystemCallFilter.java @@ -26,7 +26,6 @@ import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.Constants; @@ -39,7 +38,6 @@ import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -240,10 +238,9 @@ static class Arch { /** supported architectures map keyed by os.arch */ private static final Map ARCHITECTURES; static { - Map m = new HashMap<>(); - m.put("amd64", new Arch(0xC000003E, 0x3FFFFFFF, 57, 58, 59, 322, 317)); - m.put("aarch64", new Arch(0xC00000B7, 0xFFFFFFFF, 1079, 1071, 221, 281, 277)); - ARCHITECTURES = Collections.unmodifiableMap(m); + ARCHITECTURES = Map.of( + "amd64", new Arch(0xC000003E, 0x3FFFFFFF, 57, 58, 59, 322, 317), + "aarch64", new Arch(0xC00000B7, 0xFFFFFFFF, 1079, 1071, 221, 281, 277)); } /** invokes prctl() from linux libc library */ diff --git a/server/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java b/server/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java index d442069b57f93..9d28ea0e5bc16 100644 --- a/server/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java +++ b/server/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java @@ -23,8 +23,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; @@ -37,11 +35,13 @@ import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.Randomness; +import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; +import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.threadpool.Scheduler; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.ConnectTransportException; @@ -383,7 +383,7 @@ List establishNodeConnections(Set nodes) { } } - return Collections.unmodifiableList(new ArrayList<>(nodes)); + return List.copyOf(nodes); } } @@ -566,7 +566,7 @@ public void handleException(TransportException e) { } nodes = establishNodeConnections(newNodes); - filteredNodes = Collections.unmodifiableList(new ArrayList<>(newFilteredNodes)); + filteredNodes = List.copyOf(newFilteredNodes); } } diff --git a/server/src/main/java/org/elasticsearch/cluster/DiffableUtils.java b/server/src/main/java/org/elasticsearch/cluster/DiffableUtils.java index 725da675952f2..112856f7490d0 100644 --- a/server/src/main/java/org/elasticsearch/cluster/DiffableUtils.java +++ b/server/src/main/java/org/elasticsearch/cluster/DiffableUtils.java @@ -32,10 +32,7 @@ import java.io.IOException; 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; import java.util.Set; @@ -720,7 +717,7 @@ public void write(Set value, StreamOutput out) throws IOException { @Override public Set read(StreamInput in, K key) throws IOException { - return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(in.readStringArray()))); + return Set.of(in.readStringArray()); } } } diff --git a/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java b/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java index c46bc291e7397..3b39d283befde 100644 --- a/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java +++ b/server/src/main/java/org/elasticsearch/cluster/block/ClusterBlocks.java @@ -445,9 +445,9 @@ public ClusterBlocks build() { // We copy the block sets here in case of the builder is modified after build is called ImmutableOpenMap.Builder> indicesBuilder = ImmutableOpenMap.builder(indices.size()); for (Map.Entry> entry : indices.entrySet()) { - indicesBuilder.put(entry.getKey(), unmodifiableSet(new HashSet<>(entry.getValue()))); + indicesBuilder.put(entry.getKey(), Set.copyOf(entry.getValue())); } - return new ClusterBlocks(unmodifiableSet(new HashSet<>(global)), indicesBuilder.build()); + return new ClusterBlocks(Set.copyOf(global), indicesBuilder.build()); } } } diff --git a/server/src/main/java/org/elasticsearch/cluster/coordination/CoordinationMetaData.java b/server/src/main/java/org/elasticsearch/cluster/coordination/CoordinationMetaData.java index b63cb07feff99..244ed105257bd 100644 --- a/server/src/main/java/org/elasticsearch/cluster/coordination/CoordinationMetaData.java +++ b/server/src/main/java/org/elasticsearch/cluster/coordination/CoordinationMetaData.java @@ -94,7 +94,7 @@ public CoordinationMetaData(long term, VotingConfiguration lastCommittedConfigur this.term = term; this.lastCommittedConfiguration = lastCommittedConfiguration; this.lastAcceptedConfiguration = lastAcceptedConfiguration; - this.votingConfigExclusions = Collections.unmodifiableSet(new HashSet<>(votingConfigExclusions)); + this.votingConfigExclusions = Set.copyOf(votingConfigExclusions); } public CoordinationMetaData(StreamInput in) throws IOException { @@ -331,7 +331,7 @@ public static class VotingConfiguration implements Writeable, ToXContentFragment private final Set nodeIds; public VotingConfiguration(Set nodeIds) { - this.nodeIds = Collections.unmodifiableSet(new HashSet<>(nodeIds)); + this.nodeIds = Set.copyOf(nodeIds); } public VotingConfiguration(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java b/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java index 6fc73ef5f7fa8..807039ea882b4 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java @@ -1084,7 +1084,7 @@ public IndexMetaData build() { ImmutableOpenIntMap.Builder> filledInSyncAllocationIds = ImmutableOpenIntMap.builder(); for (int i = 0; i < numberOfShards; i++) { if (inSyncAllocationIds.containsKey(i)) { - filledInSyncAllocationIds.put(i, Collections.unmodifiableSet(new HashSet<>(inSyncAllocationIds.get(i)))); + filledInSyncAllocationIds.put(i, Set.copyOf(inSyncAllocationIds.get(i))); } else { filledInSyncAllocationIds.put(i, Collections.emptySet()); } diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java b/server/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java index 19c6d31ccc82a..ee3c2370b46f2 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java @@ -57,14 +57,10 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static java.util.Collections.unmodifiableList; - public class IndexNameExpressionResolver { private final DateMathExpressionResolver dateMathExpressionResolver = new DateMathExpressionResolver(); - private final List expressionResolvers = unmodifiableList(Arrays.asList( - dateMathExpressionResolver, - new WildcardExpressionResolver())); + private final List expressionResolvers = List.of(dateMathExpressionResolver, new WildcardExpressionResolver()); /** * Same as {@link #concreteIndexNames(ClusterState, IndicesOptions, String...)}, but the index expressions and options @@ -336,7 +332,7 @@ public Set resolveExpressions(ClusterState state, String... expressions) for (ExpressionResolver expressionResolver : expressionResolvers) { resolvedExpressions = expressionResolver.resolve(context, resolvedExpressions); } - return Collections.unmodifiableSet(new HashSet<>(resolvedExpressions)); + return Set.copyOf(resolvedExpressions); } /** diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java b/server/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java index 1c618c1ef88fd..4f182b6ca381e 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java @@ -33,7 +33,6 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; @@ -114,7 +113,7 @@ public RepositoriesMetaData(StreamInput in) throws IOException { for (int i = 0; i < repository.length; i++) { repository[i] = new RepositoryMetaData(in); } - this.repositories = Collections.unmodifiableList(Arrays.asList(repository)); + this.repositories = List.of(repository); } public static NamedDiff readDiffFrom(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java b/server/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java index c35b7d810ca0e..572cf496114aa 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/IndexShardRoutingTable.java @@ -691,7 +691,7 @@ public Builder removeShard(ShardRouting shardEntry) { public IndexShardRoutingTable build() { // don't allow more than one shard copy with same id to be allocated to same node assert distinctNodes(shards) : "more than one shard with same id assigned to same node (shards: " + shards + ")"; - return new IndexShardRoutingTable(shardId, Collections.unmodifiableList(new ArrayList<>(shards))); + return new IndexShardRoutingTable(shardId, List.copyOf(shards)); } static boolean distinctNodes(List shards) { diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/RoutingAllocation.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/RoutingAllocation.java index 059b13c5a1bd4..d49869d030eb7 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/RoutingAllocation.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/RoutingAllocation.java @@ -40,7 +40,6 @@ import java.util.Set; import static java.util.Collections.emptySet; -import static java.util.Collections.unmodifiableSet; /** * The {@link RoutingAllocation} keep the state of the current allocation @@ -215,7 +214,7 @@ public Set getIgnoreNodes(ShardId shardId) { if (ignore == null) { return emptySet(); } - return unmodifiableSet(new HashSet<>(ignore)); + return Set.copyOf(ignore); } /** diff --git a/server/src/main/java/org/elasticsearch/common/collect/MapBuilder.java b/server/src/main/java/org/elasticsearch/common/collect/MapBuilder.java index a840ee037f80e..abf27b662bb7c 100644 --- a/server/src/main/java/org/elasticsearch/common/collect/MapBuilder.java +++ b/server/src/main/java/org/elasticsearch/common/collect/MapBuilder.java @@ -22,8 +22,7 @@ import java.util.HashMap; import java.util.Map; -import static java.util.Collections.unmodifiableMap; - +// TODO: replace with usages of Map.of and Map.ofEntries public class MapBuilder { public static MapBuilder newMapBuilder() { @@ -86,6 +85,6 @@ public Map map() { */ public Map immutableMap() { // TODO: follow the directions in the Javadoc for this method - return unmodifiableMap(new HashMap<>(map)); + return Map.copyOf(map); } } diff --git a/server/src/main/java/org/elasticsearch/common/inject/internal/BindingBuilder.java b/server/src/main/java/org/elasticsearch/common/inject/internal/BindingBuilder.java index 5aa84dea58f4d..35ad7e0e8181b 100644 --- a/server/src/main/java/org/elasticsearch/common/inject/internal/BindingBuilder.java +++ b/server/src/main/java/org/elasticsearch/common/inject/internal/BindingBuilder.java @@ -27,13 +27,11 @@ import org.elasticsearch.common.inject.spi.Message; import java.lang.annotation.Annotation; -import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import static java.util.Collections.emptySet; -import static java.util.Collections.unmodifiableSet; /** * Bind a non-constant key. @@ -92,7 +90,7 @@ public void toInstance(T instance) { for (Message message : e.getErrorMessages()) { binder.addError(message); } - injectionPoints = unmodifiableSet(new HashSet(e.getPartialValue())); + injectionPoints = Set.copyOf(e.getPartialValue()); } } else { binder.addError(BINDING_TO_NULL); @@ -117,7 +115,7 @@ public BindingBuilder toProvider(Provider provider) { for (Message message : e.getErrorMessages()) { binder.addError(message); } - injectionPoints = unmodifiableSet(new HashSet(e.getPartialValue())); + injectionPoints = Set.copyOf(e.getPartialValue()); } BindingImpl base = getBinding(); diff --git a/server/src/main/java/org/elasticsearch/common/inject/internal/InstanceBindingImpl.java b/server/src/main/java/org/elasticsearch/common/inject/internal/InstanceBindingImpl.java index 7b74e6483a3ab..d3c45d8c3df4e 100644 --- a/server/src/main/java/org/elasticsearch/common/inject/internal/InstanceBindingImpl.java +++ b/server/src/main/java/org/elasticsearch/common/inject/internal/InstanceBindingImpl.java @@ -27,11 +27,8 @@ import org.elasticsearch.common.inject.spi.InstanceBinding; import org.elasticsearch.common.inject.util.Providers; -import java.util.HashSet; import java.util.Set; -import static java.util.Collections.unmodifiableSet; - public class InstanceBindingImpl extends BindingImpl implements InstanceBinding { final T instance; @@ -78,7 +75,7 @@ public Set getInjectionPoints() { @Override public Set> getDependencies() { return instance instanceof HasDependencies - ? unmodifiableSet(new HashSet<>((((HasDependencies) instance).getDependencies()))) + ? Set.copyOf(((HasDependencies) instance).getDependencies()) : Dependency.forInjectionPoints(injectionPoints); } diff --git a/server/src/main/java/org/elasticsearch/common/inject/internal/ProviderInstanceBindingImpl.java b/server/src/main/java/org/elasticsearch/common/inject/internal/ProviderInstanceBindingImpl.java index e95d8fe491b69..cab8a8b8088c8 100644 --- a/server/src/main/java/org/elasticsearch/common/inject/internal/ProviderInstanceBindingImpl.java +++ b/server/src/main/java/org/elasticsearch/common/inject/internal/ProviderInstanceBindingImpl.java @@ -26,11 +26,8 @@ import org.elasticsearch.common.inject.spi.InjectionPoint; import org.elasticsearch.common.inject.spi.ProviderInstanceBinding; -import java.util.HashSet; import java.util.Set; -import static java.util.Collections.unmodifiableSet; - public final class ProviderInstanceBindingImpl extends BindingImpl implements ProviderInstanceBinding { @@ -71,7 +68,7 @@ public Set getInjectionPoints() { @Override public Set> getDependencies() { return providerInstance instanceof HasDependencies - ? unmodifiableSet(new HashSet<>((((HasDependencies) providerInstance).getDependencies()))) + ? Set.copyOf(((HasDependencies) providerInstance).getDependencies()) : Dependency.forInjectionPoints(injectionPoints); } diff --git a/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java b/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java index 1c9dfd7ea4433..5cd13be2c3087 100644 --- a/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java +++ b/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java @@ -55,16 +55,14 @@ import java.nio.file.FileSystemLoopException; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; -import java.time.ZoneId; import java.time.Instant; +import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumMap; import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -140,7 +138,7 @@ public boolean hasFeature(final String feature) { */ public void setFeatures(final Set features) { assert this.features.isEmpty() : this.features; - this.features = Collections.unmodifiableSet(new HashSet<>(features)); + this.features = Set.copyOf(features); } public long position() throws IOException { @@ -597,124 +595,99 @@ public final void writeOptionalInstant(@Nullable Instant instant) throws IOExcep private static final Map, Writer> WRITERS; static { - Map, Writer> writers = new HashMap<>(); - writers.put(String.class, (o, v) -> { + WRITERS = Map.ofEntries(Map.entry(String.class, (o, v) -> { o.writeByte((byte) 0); o.writeString((String) v); - }); - writers.put(Integer.class, (o, v) -> { + }), Map.entry(Integer.class, (o, v) -> { o.writeByte((byte) 1); o.writeInt((Integer) v); - }); - writers.put(Long.class, (o, v) -> { + }), Map.entry(Long.class, (o, v) -> { o.writeByte((byte) 2); o.writeLong((Long) v); - }); - writers.put(Float.class, (o, v) -> { + }), Map.entry(Float.class, (o, v) -> { o.writeByte((byte) 3); o.writeFloat((float) v); - }); - writers.put(Double.class, (o, v) -> { + }), Map.entry(Double.class, (o, v) -> { o.writeByte((byte) 4); o.writeDouble((double) v); - }); - writers.put(Boolean.class, (o, v) -> { + }), Map.entry(Boolean.class, (o, v) -> { o.writeByte((byte) 5); o.writeBoolean((boolean) v); - }); - writers.put(byte[].class, (o, v) -> { + }), Map.entry(byte[].class, (o, v) -> { o.writeByte((byte) 6); final byte[] bytes = (byte[]) v; o.writeVInt(bytes.length); o.writeBytes(bytes); - }); - writers.put(List.class, (o, v) -> { + }), Map.entry(List.class, (o, v) -> { o.writeByte((byte) 7); final List list = (List) v; o.writeVInt(list.size()); for (Object item : list) { o.writeGenericValue(item); } - }); - writers.put(Object[].class, (o, v) -> { + }), Map.entry(Object[].class, (o, v) -> { o.writeByte((byte) 8); final Object[] list = (Object[]) v; o.writeVInt(list.length); for (Object item : list) { o.writeGenericValue(item); } - }); - writers.put(Map.class, (o, v) -> { + }), Map.entry(Map.class, (o, v) -> { if (v instanceof LinkedHashMap) { o.writeByte((byte) 9); } else { o.writeByte((byte) 10); } - @SuppressWarnings("unchecked") - final Map map = (Map) v; + @SuppressWarnings("unchecked") final Map map = (Map) v; o.writeVInt(map.size()); for (Map.Entry entry : map.entrySet()) { o.writeString(entry.getKey()); o.writeGenericValue(entry.getValue()); } - }); - writers.put(Byte.class, (o, v) -> { + }), Map.entry(Byte.class, (o, v) -> { o.writeByte((byte) 11); o.writeByte((Byte) v); - }); - writers.put(Date.class, (o, v) -> { + }), Map.entry(Date.class, (o, v) -> { o.writeByte((byte) 12); o.writeLong(((Date) v).getTime()); - }); - writers.put(ReadableInstant.class, (o, v) -> { + }), Map.entry(ReadableInstant.class, (o, v) -> { o.writeByte((byte) 13); final ReadableInstant instant = (ReadableInstant) v; o.writeString(instant.getZone().getID()); o.writeLong(instant.getMillis()); - }); - writers.put(BytesReference.class, (o, v) -> { + }), Map.entry(BytesReference.class, (o, v) -> { o.writeByte((byte) 14); o.writeBytesReference((BytesReference) v); - }); - writers.put(Text.class, (o, v) -> { + }), Map.entry(Text.class, (o, v) -> { o.writeByte((byte) 15); o.writeText((Text) v); - }); - writers.put(Short.class, (o, v) -> { + }), Map.entry(Short.class, (o, v) -> { o.writeByte((byte) 16); o.writeShort((Short) v); - }); - writers.put(int[].class, (o, v) -> { + }), Map.entry(int[].class, (o, v) -> { o.writeByte((byte) 17); o.writeIntArray((int[]) v); - }); - writers.put(long[].class, (o, v) -> { + }), Map.entry(long[].class, (o, v) -> { o.writeByte((byte) 18); o.writeLongArray((long[]) v); - }); - writers.put(float[].class, (o, v) -> { + }), Map.entry(float[].class, (o, v) -> { o.writeByte((byte) 19); o.writeFloatArray((float[]) v); - }); - writers.put(double[].class, (o, v) -> { + }), Map.entry(double[].class, (o, v) -> { o.writeByte((byte) 20); o.writeDoubleArray((double[]) v); - }); - writers.put(BytesRef.class, (o, v) -> { + }), Map.entry(BytesRef.class, (o, v) -> { o.writeByte((byte) 21); o.writeBytesRef((BytesRef) v); - }); - writers.put(GeoPoint.class, (o, v) -> { + }), Map.entry(GeoPoint.class, (o, v) -> { o.writeByte((byte) 22); o.writeGeoPoint((GeoPoint) v); - }); - writers.put(ZonedDateTime.class, (o, v) -> { + }), Map.entry(ZonedDateTime.class, (o, v) -> { o.writeByte((byte) 23); final ZonedDateTime zonedDateTime = (ZonedDateTime) v; o.writeString(zonedDateTime.getZone().getId()); o.writeLong(zonedDateTime.toInstant().toEpochMilli()); - }); - writers.put(JodaCompatibleZonedDateTime.class, (o, v) -> { + }), Map.entry(JodaCompatibleZonedDateTime.class, (o, v) -> { // write the joda compatibility datetime as joda datetime o.writeByte((byte) 13); final JodaCompatibleZonedDateTime zonedDateTime = (JodaCompatibleZonedDateTime) v; @@ -722,8 +695,7 @@ public final void writeOptionalInstant(@Nullable Instant instant) throws IOExcep // joda does not understand "Z" for utc, so we must special case o.writeString(zoneId.equals("Z") ? DateTimeZone.UTC.getID() : zoneId); o.writeLong(zonedDateTime.toInstant().toEpochMilli()); - }); - WRITERS = Collections.unmodifiableMap(writers); + })); } /** diff --git a/server/src/main/java/org/elasticsearch/common/lucene/ShardCoreKeyMap.java b/server/src/main/java/org/elasticsearch/common/lucene/ShardCoreKeyMap.java index 93b7907812bb8..3ea9a9525dc1f 100644 --- a/server/src/main/java/org/elasticsearch/common/lucene/ShardCoreKeyMap.java +++ b/server/src/main/java/org/elasticsearch/common/lucene/ShardCoreKeyMap.java @@ -141,7 +141,7 @@ public synchronized Set getCoreKeysForIndex(String index) { return Collections.emptySet(); } // we have to copy otherwise we risk ConcurrentModificationException - return Collections.unmodifiableSet(new HashSet<>(objects)); + return Set.copyOf(objects); } /** diff --git a/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java b/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java index 9d3e278e889f6..998e4e123a975 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java +++ b/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java @@ -116,7 +116,7 @@ protected AbstractScopedSettings(Settings nodeSettings, Settings scopeSettings, this.scope = other.scope; complexMatchers = other.complexMatchers; keySettings = other.keySettings; - settingUpgraders = Collections.unmodifiableMap(new HashMap<>(other.settingUpgraders)); + settingUpgraders = Map.copyOf(other.settingUpgraders); settingUpdaters.addAll(other.settingUpdaters); } diff --git a/server/src/main/java/org/elasticsearch/common/settings/ClusterSettings.java b/server/src/main/java/org/elasticsearch/common/settings/ClusterSettings.java index 82ae117c3e24b..6b50c0f1c112c 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/ClusterSettings.java +++ b/server/src/main/java/org/elasticsearch/common/settings/ClusterSettings.java @@ -104,9 +104,7 @@ import org.elasticsearch.transport.TransportSettings; import org.elasticsearch.watcher.ResourceWatcherService; -import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; @@ -176,289 +174,287 @@ public void apply(Settings value, Settings current, Settings previous) { } } - public static Set> BUILT_IN_CLUSTER_SETTINGS = Collections.unmodifiableSet(new HashSet<>( - Arrays.asList(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING, - TransportClient.CLIENT_TRANSPORT_NODES_SAMPLER_INTERVAL, // TODO these transport client settings are kind - // of odd here and should only be valid if we are a transport client - TransportClient.CLIENT_TRANSPORT_PING_TIMEOUT, - TransportClient.CLIENT_TRANSPORT_IGNORE_CLUSTER_NAME, - TransportClient.CLIENT_TRANSPORT_SNIFF, - AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP_SETTING, - BalancedShardsAllocator.INDEX_BALANCE_FACTOR_SETTING, - BalancedShardsAllocator.SHARD_BALANCE_FACTOR_SETTING, - BalancedShardsAllocator.THRESHOLD_SETTING, - ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE_SETTING, - ConcurrentRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_CLUSTER_CONCURRENT_REBALANCE_SETTING, - EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING, - EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING, - FilterAllocationDecider.CLUSTER_ROUTING_INCLUDE_GROUP_SETTING, - FilterAllocationDecider.CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING, - FilterAllocationDecider.CLUSTER_ROUTING_REQUIRE_GROUP_SETTING, - FsRepository.REPOSITORIES_CHUNK_SIZE_SETTING, - FsRepository.REPOSITORIES_LOCATION_SETTING, - IndicesQueryCache.INDICES_CACHE_QUERY_SIZE_SETTING, - IndicesQueryCache.INDICES_CACHE_QUERY_COUNT_SETTING, - IndicesQueryCache.INDICES_QUERIES_CACHE_ALL_SEGMENTS_SETTING, - MappingUpdatedAction.INDICES_MAPPING_DYNAMIC_TIMEOUT_SETTING, - MetaData.SETTING_READ_ONLY_SETTING, - MetaData.SETTING_READ_ONLY_ALLOW_DELETE_SETTING, - MetaData.SETTING_CLUSTER_MAX_SHARDS_PER_NODE, - RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING, - RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING, - RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING, - RecoverySettings.INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING, - RecoverySettings.INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING, - RecoverySettings.INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING, - RecoverySettings.INDICES_RECOVERY_MAX_CONCURRENT_FILE_CHUNKS_SETTING, - ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING, - ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_INCOMING_RECOVERIES_SETTING, - ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_OUTGOING_RECOVERIES_SETTING, - ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING, - DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING, - DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING, - DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_WATERMARK_SETTING, - DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING, - DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_INCLUDE_RELOCATIONS_SETTING, - DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL_SETTING, - SameShardAllocationDecider.CLUSTER_ROUTING_ALLOCATION_SAME_HOST_SETTING, - InternalClusterInfoService.INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING, - InternalClusterInfoService.INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING, - DestructiveOperations.REQUIRES_NAME_SETTING, - NoMasterBlockService.NO_MASTER_BLOCK_SETTING, - GatewayService.EXPECTED_DATA_NODES_SETTING, - GatewayService.EXPECTED_MASTER_NODES_SETTING, - GatewayService.EXPECTED_NODES_SETTING, - GatewayService.RECOVER_AFTER_DATA_NODES_SETTING, - GatewayService.RECOVER_AFTER_MASTER_NODES_SETTING, - GatewayService.RECOVER_AFTER_NODES_SETTING, - GatewayService.RECOVER_AFTER_TIME_SETTING, - NetworkModule.HTTP_DEFAULT_TYPE_SETTING, - NetworkModule.TRANSPORT_DEFAULT_TYPE_SETTING, - NetworkModule.HTTP_TYPE_SETTING, - NetworkModule.TRANSPORT_TYPE_SETTING, - HttpTransportSettings.SETTING_CORS_ALLOW_CREDENTIALS, - HttpTransportSettings.SETTING_CORS_ENABLED, - HttpTransportSettings.SETTING_CORS_MAX_AGE, - HttpTransportSettings.SETTING_HTTP_DETAILED_ERRORS_ENABLED, - HttpTransportSettings.SETTING_CORS_ALLOW_ORIGIN, - HttpTransportSettings.SETTING_HTTP_HOST, - HttpTransportSettings.SETTING_HTTP_PUBLISH_HOST, - HttpTransportSettings.SETTING_HTTP_BIND_HOST, - HttpTransportSettings.SETTING_HTTP_PORT, - HttpTransportSettings.SETTING_HTTP_PUBLISH_PORT, - HttpTransportSettings.SETTING_PIPELINING_MAX_EVENTS, - HttpTransportSettings.SETTING_HTTP_COMPRESSION, - HttpTransportSettings.SETTING_HTTP_COMPRESSION_LEVEL, - HttpTransportSettings.SETTING_CORS_ALLOW_METHODS, - HttpTransportSettings.SETTING_CORS_ALLOW_HEADERS, - HttpTransportSettings.SETTING_HTTP_DETAILED_ERRORS_ENABLED, - HttpTransportSettings.SETTING_HTTP_CONTENT_TYPE_REQUIRED, - HttpTransportSettings.SETTING_HTTP_MAX_CONTENT_LENGTH, - HttpTransportSettings.SETTING_HTTP_MAX_CHUNK_SIZE, - HttpTransportSettings.SETTING_HTTP_MAX_HEADER_SIZE, - HttpTransportSettings.SETTING_HTTP_MAX_WARNING_HEADER_COUNT, - HttpTransportSettings.SETTING_HTTP_MAX_WARNING_HEADER_SIZE, - HttpTransportSettings.SETTING_HTTP_MAX_INITIAL_LINE_LENGTH, - HttpTransportSettings.SETTING_HTTP_READ_TIMEOUT, - HttpTransportSettings.SETTING_HTTP_RESET_COOKIES, - HttpTransportSettings.SETTING_HTTP_TCP_NO_DELAY, - HttpTransportSettings.SETTING_HTTP_TCP_KEEP_ALIVE, - HttpTransportSettings.SETTING_HTTP_TCP_REUSE_ADDRESS, - HttpTransportSettings.SETTING_HTTP_TCP_SEND_BUFFER_SIZE, - HttpTransportSettings.SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE, - HierarchyCircuitBreakerService.USE_REAL_MEMORY_USAGE_SETTING, - HierarchyCircuitBreakerService.TOTAL_CIRCUIT_BREAKER_LIMIT_SETTING, - HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, - HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, - HierarchyCircuitBreakerService.IN_FLIGHT_REQUESTS_CIRCUIT_BREAKER_LIMIT_SETTING, - HierarchyCircuitBreakerService.IN_FLIGHT_REQUESTS_CIRCUIT_BREAKER_OVERHEAD_SETTING, - HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING, - HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_OVERHEAD_SETTING, - HierarchyCircuitBreakerService.ACCOUNTING_CIRCUIT_BREAKER_LIMIT_SETTING, - HierarchyCircuitBreakerService.ACCOUNTING_CIRCUIT_BREAKER_OVERHEAD_SETTING, - IndexModule.NODE_STORE_ALLOW_MMAP, - ClusterService.CLUSTER_SERVICE_SLOW_TASK_LOGGING_THRESHOLD_SETTING, - ClusterService.USER_DEFINED_META_DATA, - SearchService.DEFAULT_SEARCH_TIMEOUT_SETTING, - SearchService.DEFAULT_ALLOW_PARTIAL_SEARCH_RESULTS, - TransportSearchAction.SHARD_COUNT_LIMIT_SETTING, - RemoteClusterAware.REMOTE_CLUSTERS_SEEDS, - RemoteClusterAware.SEARCH_REMOTE_CLUSTERS_SEEDS, - RemoteClusterAware.REMOTE_CLUSTERS_PROXY, - RemoteClusterAware.SEARCH_REMOTE_CLUSTERS_PROXY, - RemoteClusterService.REMOTE_CLUSTER_SKIP_UNAVAILABLE, - RemoteClusterService.SEARCH_REMOTE_CLUSTER_SKIP_UNAVAILABLE, - RemoteClusterService.REMOTE_CONNECTIONS_PER_CLUSTER, - RemoteClusterService.SEARCH_REMOTE_CONNECTIONS_PER_CLUSTER, - RemoteClusterService.REMOTE_INITIAL_CONNECTION_TIMEOUT_SETTING, - RemoteClusterService.SEARCH_REMOTE_INITIAL_CONNECTION_TIMEOUT_SETTING, - RemoteClusterService.REMOTE_NODE_ATTRIBUTE, - RemoteClusterService.SEARCH_REMOTE_NODE_ATTRIBUTE, - RemoteClusterService.ENABLE_REMOTE_CLUSTERS, - RemoteClusterService.SEARCH_ENABLE_REMOTE_CLUSTERS, - RemoteClusterService.REMOTE_CLUSTER_PING_SCHEDULE, - RemoteClusterService.REMOTE_CLUSTER_COMPRESS, - TransportCloseIndexAction.CLUSTER_INDICES_CLOSE_ENABLE_SETTING, - ShardsLimitAllocationDecider.CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING, - NodeConnectionsService.CLUSTER_NODE_RECONNECT_INTERVAL_SETTING, - HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_TYPE_SETTING, - HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_TYPE_SETTING, - TransportSettings.HOST, - TransportSettings.PUBLISH_HOST, - TransportSettings.PUBLISH_HOST_PROFILE, - TransportSettings.BIND_HOST, - TransportSettings.BIND_HOST_PROFILE, - TransportSettings.PORT, - TransportSettings.PORT_PROFILE, - TransportSettings.PUBLISH_PORT, - TransportSettings.PUBLISH_PORT_PROFILE, - TransportSettings.TRANSPORT_COMPRESS, - TransportSettings.PING_SCHEDULE, - TransportSettings.CONNECT_TIMEOUT, - TransportSettings.DEFAULT_FEATURES_SETTING, - TransportSettings.TCP_NO_DELAY, - TransportSettings.TCP_NO_DELAY_PROFILE, - TransportSettings.TCP_KEEP_ALIVE, - TransportSettings.TCP_KEEP_ALIVE_PROFILE, - TransportSettings.TCP_REUSE_ADDRESS, - TransportSettings.TCP_REUSE_ADDRESS_PROFILE, - TransportSettings.TCP_SEND_BUFFER_SIZE, - TransportSettings.TCP_SEND_BUFFER_SIZE_PROFILE, - TransportSettings.TCP_RECEIVE_BUFFER_SIZE, - TransportSettings.TCP_RECEIVE_BUFFER_SIZE_PROFILE, - TransportSettings.CONNECTIONS_PER_NODE_RECOVERY, - TransportSettings.CONNECTIONS_PER_NODE_BULK, - TransportSettings.CONNECTIONS_PER_NODE_REG, - TransportSettings.CONNECTIONS_PER_NODE_STATE, - TransportSettings.CONNECTIONS_PER_NODE_PING, - TransportSettings.TRACE_LOG_EXCLUDE_SETTING, - TransportSettings.TRACE_LOG_INCLUDE_SETTING, - NetworkService.NETWORK_SERVER, - NetworkService.GLOBAL_NETWORK_HOST_SETTING, - NetworkService.GLOBAL_NETWORK_BIND_HOST_SETTING, - NetworkService.GLOBAL_NETWORK_PUBLISH_HOST_SETTING, - NetworkService.TCP_NO_DELAY, - NetworkService.TCP_KEEP_ALIVE, - NetworkService.TCP_REUSE_ADDRESS, - NetworkService.TCP_SEND_BUFFER_SIZE, - NetworkService.TCP_RECEIVE_BUFFER_SIZE, - IndexSettings.QUERY_STRING_ANALYZE_WILDCARD, - IndexSettings.QUERY_STRING_ALLOW_LEADING_WILDCARD, - ScriptService.SCRIPT_CACHE_SIZE_SETTING, - ScriptService.SCRIPT_CACHE_EXPIRE_SETTING, - ScriptService.SCRIPT_MAX_SIZE_IN_BYTES, - ScriptService.SCRIPT_MAX_COMPILATIONS_RATE, - ScriptService.TYPES_ALLOWED_SETTING, - ScriptService.CONTEXTS_ALLOWED_SETTING, - IndicesService.INDICES_CACHE_CLEAN_INTERVAL_SETTING, - IndicesFieldDataCache.INDICES_FIELDDATA_CACHE_SIZE_KEY, - IndicesRequestCache.INDICES_CACHE_QUERY_SIZE, - IndicesRequestCache.INDICES_CACHE_QUERY_EXPIRE, - HunspellService.HUNSPELL_LAZY_LOAD, - HunspellService.HUNSPELL_IGNORE_CASE, - HunspellService.HUNSPELL_DICTIONARY_OPTIONS, - IndicesStore.INDICES_STORE_DELETE_SHARD_TIMEOUT, - Environment.PATH_DATA_SETTING, - Environment.PATH_HOME_SETTING, - Environment.PATH_LOGS_SETTING, - Environment.PATH_REPO_SETTING, - Environment.PATH_SHARED_DATA_SETTING, - Environment.PIDFILE_SETTING, - NodeEnvironment.NODE_ID_SEED_SETTING, - Node.INITIAL_STATE_TIMEOUT_SETTING, - DiscoveryModule.DISCOVERY_TYPE_SETTING, - DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING, - SettingsBasedSeedHostsProvider.DISCOVERY_SEED_HOSTS_SETTING, - SeedHostsResolver.DISCOVERY_SEED_RESOLVER_MAX_CONCURRENT_RESOLVERS_SETTING, - SeedHostsResolver.DISCOVERY_SEED_RESOLVER_TIMEOUT_SETTING, - SearchService.DEFAULT_KEEPALIVE_SETTING, - SearchService.KEEPALIVE_INTERVAL_SETTING, - SearchService.MAX_KEEPALIVE_SETTING, - MultiBucketConsumerService.MAX_BUCKET_SETTING, - SearchService.LOW_LEVEL_CANCELLATION_SETTING, - SearchService.MAX_OPEN_SCROLL_CONTEXT, - Node.WRITE_PORTS_FILE_SETTING, - Node.NODE_NAME_SETTING, - Node.NODE_DATA_SETTING, - Node.NODE_MASTER_SETTING, - Node.NODE_INGEST_SETTING, - Node.NODE_ATTRIBUTES, - Node.NODE_LOCAL_STORAGE_SETTING, - AutoCreateIndex.AUTO_CREATE_INDEX_SETTING, - BaseRestHandler.MULTI_ALLOW_EXPLICIT_INDEX, - ClusterName.CLUSTER_NAME_SETTING, - Client.CLIENT_TYPE_SETTING_S, - ClusterModule.SHARDS_ALLOCATOR_TYPE_SETTING, - EsExecutors.PROCESSORS_SETTING, - ThreadContext.DEFAULT_HEADERS_SETTING, - Loggers.LOG_DEFAULT_LEVEL_SETTING, - Loggers.LOG_LEVEL_SETTING, - NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING, - NodeEnvironment.ENABLE_LUCENE_SEGMENT_INFOS_TRACE_SETTING, - OsService.REFRESH_INTERVAL_SETTING, - ProcessService.REFRESH_INTERVAL_SETTING, - JvmService.REFRESH_INTERVAL_SETTING, - FsService.REFRESH_INTERVAL_SETTING, - JvmGcMonitorService.ENABLED_SETTING, - JvmGcMonitorService.REFRESH_INTERVAL_SETTING, - JvmGcMonitorService.GC_SETTING, - JvmGcMonitorService.GC_OVERHEAD_WARN_SETTING, - JvmGcMonitorService.GC_OVERHEAD_INFO_SETTING, - JvmGcMonitorService.GC_OVERHEAD_DEBUG_SETTING, - PageCacheRecycler.LIMIT_HEAP_SETTING, - PageCacheRecycler.WEIGHT_BYTES_SETTING, - PageCacheRecycler.WEIGHT_INT_SETTING, - PageCacheRecycler.WEIGHT_LONG_SETTING, - PageCacheRecycler.WEIGHT_OBJECTS_SETTING, - PageCacheRecycler.TYPE_SETTING, - PluginsService.MANDATORY_SETTING, - BootstrapSettings.SECURITY_FILTER_BAD_DEFAULTS_SETTING, - BootstrapSettings.MEMORY_LOCK_SETTING, - BootstrapSettings.SYSTEM_CALL_FILTER_SETTING, - BootstrapSettings.CTRLHANDLER_SETTING, - KeyStoreWrapper.SEED_SETTING, - IndexingMemoryController.INDEX_BUFFER_SIZE_SETTING, - IndexingMemoryController.MIN_INDEX_BUFFER_SIZE_SETTING, - IndexingMemoryController.MAX_INDEX_BUFFER_SIZE_SETTING, - IndexingMemoryController.SHARD_INACTIVE_TIME_SETTING, - IndexingMemoryController.SHARD_MEMORY_INTERVAL_TIME_SETTING, - ResourceWatcherService.ENABLED, - ResourceWatcherService.RELOAD_INTERVAL_HIGH, - ResourceWatcherService.RELOAD_INTERVAL_MEDIUM, - ResourceWatcherService.RELOAD_INTERVAL_LOW, - SearchModule.INDICES_MAX_CLAUSE_COUNT_SETTING, - ThreadPool.ESTIMATED_TIME_INTERVAL_SETTING, - FastVectorHighlighter.SETTING_TV_HIGHLIGHT_MULTI_VALUE, - Node.BREAKER_TYPE_KEY, - OperationRouting.USE_ADAPTIVE_REPLICA_SELECTION_SETTING, - IndexGraveyard.SETTING_MAX_TOMBSTONES, - PersistentTasksClusterService.CLUSTER_TASKS_ALLOCATION_RECHECK_INTERVAL_SETTING, - EnableAssignmentDecider.CLUSTER_TASKS_ALLOCATION_ENABLE_SETTING, - PeerFinder.DISCOVERY_FIND_PEERS_INTERVAL_SETTING, - PeerFinder.DISCOVERY_REQUEST_PEERS_TIMEOUT_SETTING, - ClusterFormationFailureHelper.DISCOVERY_CLUSTER_FORMATION_WARNING_TIMEOUT_SETTING, - ElectionSchedulerFactory.ELECTION_INITIAL_TIMEOUT_SETTING, - ElectionSchedulerFactory.ELECTION_BACK_OFF_TIME_SETTING, - ElectionSchedulerFactory.ELECTION_MAX_TIMEOUT_SETTING, - ElectionSchedulerFactory.ELECTION_DURATION_SETTING, - Coordinator.PUBLISH_TIMEOUT_SETTING, - JoinHelper.JOIN_TIMEOUT_SETTING, - FollowersChecker.FOLLOWER_CHECK_TIMEOUT_SETTING, - FollowersChecker.FOLLOWER_CHECK_INTERVAL_SETTING, - FollowersChecker.FOLLOWER_CHECK_RETRY_COUNT_SETTING, - LeaderChecker.LEADER_CHECK_TIMEOUT_SETTING, - LeaderChecker.LEADER_CHECK_INTERVAL_SETTING, - LeaderChecker.LEADER_CHECK_RETRY_COUNT_SETTING, - Reconfigurator.CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION, - TransportAddVotingConfigExclusionsAction.MAXIMUM_VOTING_CONFIG_EXCLUSIONS_SETTING, - ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING, - ClusterBootstrapService.UNCONFIGURED_BOOTSTRAP_TIMEOUT_SETTING, - LagDetector.CLUSTER_FOLLOWER_LAG_TIMEOUT_SETTING - ))); + public static Set> BUILT_IN_CLUSTER_SETTINGS = Set.of( + AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING, + // TODO these transport client settings are kind of odd here and should only be valid if we are a transport client + TransportClient.CLIENT_TRANSPORT_NODES_SAMPLER_INTERVAL, + TransportClient.CLIENT_TRANSPORT_PING_TIMEOUT, + TransportClient.CLIENT_TRANSPORT_IGNORE_CLUSTER_NAME, + TransportClient.CLIENT_TRANSPORT_SNIFF, + AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP_SETTING, + BalancedShardsAllocator.INDEX_BALANCE_FACTOR_SETTING, + BalancedShardsAllocator.SHARD_BALANCE_FACTOR_SETTING, + BalancedShardsAllocator.THRESHOLD_SETTING, + ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE_SETTING, + ConcurrentRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_CLUSTER_CONCURRENT_REBALANCE_SETTING, + EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING, + EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING, + FilterAllocationDecider.CLUSTER_ROUTING_INCLUDE_GROUP_SETTING, + FilterAllocationDecider.CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING, + FilterAllocationDecider.CLUSTER_ROUTING_REQUIRE_GROUP_SETTING, + FsRepository.REPOSITORIES_CHUNK_SIZE_SETTING, + FsRepository.REPOSITORIES_LOCATION_SETTING, + IndicesQueryCache.INDICES_CACHE_QUERY_SIZE_SETTING, + IndicesQueryCache.INDICES_CACHE_QUERY_COUNT_SETTING, + IndicesQueryCache.INDICES_QUERIES_CACHE_ALL_SEGMENTS_SETTING, + MappingUpdatedAction.INDICES_MAPPING_DYNAMIC_TIMEOUT_SETTING, + MetaData.SETTING_READ_ONLY_SETTING, + MetaData.SETTING_READ_ONLY_ALLOW_DELETE_SETTING, + MetaData.SETTING_CLUSTER_MAX_SHARDS_PER_NODE, + RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING, + RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING, + RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING, + RecoverySettings.INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING, + RecoverySettings.INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING, + RecoverySettings.INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING, + RecoverySettings.INDICES_RECOVERY_MAX_CONCURRENT_FILE_CHUNKS_SETTING, + ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING, + ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_INCOMING_RECOVERIES_SETTING, + ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_OUTGOING_RECOVERIES_SETTING, + ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING, + DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING, + DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING, + DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_WATERMARK_SETTING, + DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING, + DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_INCLUDE_RELOCATIONS_SETTING, + DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL_SETTING, + SameShardAllocationDecider.CLUSTER_ROUTING_ALLOCATION_SAME_HOST_SETTING, + InternalClusterInfoService.INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING, + InternalClusterInfoService.INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING, + DestructiveOperations.REQUIRES_NAME_SETTING, + NoMasterBlockService.NO_MASTER_BLOCK_SETTING, + GatewayService.EXPECTED_DATA_NODES_SETTING, + GatewayService.EXPECTED_MASTER_NODES_SETTING, + GatewayService.EXPECTED_NODES_SETTING, + GatewayService.RECOVER_AFTER_DATA_NODES_SETTING, + GatewayService.RECOVER_AFTER_MASTER_NODES_SETTING, + GatewayService.RECOVER_AFTER_NODES_SETTING, + GatewayService.RECOVER_AFTER_TIME_SETTING, + NetworkModule.HTTP_DEFAULT_TYPE_SETTING, + NetworkModule.TRANSPORT_DEFAULT_TYPE_SETTING, + NetworkModule.HTTP_TYPE_SETTING, + NetworkModule.TRANSPORT_TYPE_SETTING, + HttpTransportSettings.SETTING_CORS_ALLOW_CREDENTIALS, + HttpTransportSettings.SETTING_CORS_ENABLED, + HttpTransportSettings.SETTING_CORS_MAX_AGE, + HttpTransportSettings.SETTING_CORS_ALLOW_ORIGIN, + HttpTransportSettings.SETTING_HTTP_HOST, + HttpTransportSettings.SETTING_HTTP_PUBLISH_HOST, + HttpTransportSettings.SETTING_HTTP_BIND_HOST, + HttpTransportSettings.SETTING_HTTP_PORT, + HttpTransportSettings.SETTING_HTTP_PUBLISH_PORT, + HttpTransportSettings.SETTING_PIPELINING_MAX_EVENTS, + HttpTransportSettings.SETTING_HTTP_COMPRESSION, + HttpTransportSettings.SETTING_HTTP_COMPRESSION_LEVEL, + HttpTransportSettings.SETTING_CORS_ALLOW_METHODS, + HttpTransportSettings.SETTING_CORS_ALLOW_HEADERS, + HttpTransportSettings.SETTING_HTTP_DETAILED_ERRORS_ENABLED, + HttpTransportSettings.SETTING_HTTP_CONTENT_TYPE_REQUIRED, + HttpTransportSettings.SETTING_HTTP_MAX_CONTENT_LENGTH, + HttpTransportSettings.SETTING_HTTP_MAX_CHUNK_SIZE, + HttpTransportSettings.SETTING_HTTP_MAX_HEADER_SIZE, + HttpTransportSettings.SETTING_HTTP_MAX_WARNING_HEADER_COUNT, + HttpTransportSettings.SETTING_HTTP_MAX_WARNING_HEADER_SIZE, + HttpTransportSettings.SETTING_HTTP_MAX_INITIAL_LINE_LENGTH, + HttpTransportSettings.SETTING_HTTP_READ_TIMEOUT, + HttpTransportSettings.SETTING_HTTP_RESET_COOKIES, + HttpTransportSettings.SETTING_HTTP_TCP_NO_DELAY, + HttpTransportSettings.SETTING_HTTP_TCP_KEEP_ALIVE, + HttpTransportSettings.SETTING_HTTP_TCP_REUSE_ADDRESS, + HttpTransportSettings.SETTING_HTTP_TCP_SEND_BUFFER_SIZE, + HttpTransportSettings.SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE, + HierarchyCircuitBreakerService.USE_REAL_MEMORY_USAGE_SETTING, + HierarchyCircuitBreakerService.TOTAL_CIRCUIT_BREAKER_LIMIT_SETTING, + HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, + HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, + HierarchyCircuitBreakerService.IN_FLIGHT_REQUESTS_CIRCUIT_BREAKER_LIMIT_SETTING, + HierarchyCircuitBreakerService.IN_FLIGHT_REQUESTS_CIRCUIT_BREAKER_OVERHEAD_SETTING, + HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING, + HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_OVERHEAD_SETTING, + HierarchyCircuitBreakerService.ACCOUNTING_CIRCUIT_BREAKER_LIMIT_SETTING, + HierarchyCircuitBreakerService.ACCOUNTING_CIRCUIT_BREAKER_OVERHEAD_SETTING, + IndexModule.NODE_STORE_ALLOW_MMAP, + ClusterService.CLUSTER_SERVICE_SLOW_TASK_LOGGING_THRESHOLD_SETTING, + ClusterService.USER_DEFINED_META_DATA, + SearchService.DEFAULT_SEARCH_TIMEOUT_SETTING, + SearchService.DEFAULT_ALLOW_PARTIAL_SEARCH_RESULTS, + TransportSearchAction.SHARD_COUNT_LIMIT_SETTING, + RemoteClusterAware.REMOTE_CLUSTERS_SEEDS, + RemoteClusterAware.SEARCH_REMOTE_CLUSTERS_SEEDS, + RemoteClusterAware.REMOTE_CLUSTERS_PROXY, + RemoteClusterAware.SEARCH_REMOTE_CLUSTERS_PROXY, + RemoteClusterService.REMOTE_CLUSTER_SKIP_UNAVAILABLE, + RemoteClusterService.SEARCH_REMOTE_CLUSTER_SKIP_UNAVAILABLE, + RemoteClusterService.REMOTE_CONNECTIONS_PER_CLUSTER, + RemoteClusterService.SEARCH_REMOTE_CONNECTIONS_PER_CLUSTER, + RemoteClusterService.REMOTE_INITIAL_CONNECTION_TIMEOUT_SETTING, + RemoteClusterService.SEARCH_REMOTE_INITIAL_CONNECTION_TIMEOUT_SETTING, + RemoteClusterService.REMOTE_NODE_ATTRIBUTE, + RemoteClusterService.SEARCH_REMOTE_NODE_ATTRIBUTE, + RemoteClusterService.ENABLE_REMOTE_CLUSTERS, + RemoteClusterService.SEARCH_ENABLE_REMOTE_CLUSTERS, + RemoteClusterService.REMOTE_CLUSTER_PING_SCHEDULE, + RemoteClusterService.REMOTE_CLUSTER_COMPRESS, + TransportCloseIndexAction.CLUSTER_INDICES_CLOSE_ENABLE_SETTING, + ShardsLimitAllocationDecider.CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING, + NodeConnectionsService.CLUSTER_NODE_RECONNECT_INTERVAL_SETTING, + HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_TYPE_SETTING, + HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_TYPE_SETTING, + TransportSettings.HOST, + TransportSettings.PUBLISH_HOST, + TransportSettings.PUBLISH_HOST_PROFILE, + TransportSettings.BIND_HOST, + TransportSettings.BIND_HOST_PROFILE, + TransportSettings.PORT, + TransportSettings.PORT_PROFILE, + TransportSettings.PUBLISH_PORT, + TransportSettings.PUBLISH_PORT_PROFILE, + TransportSettings.TRANSPORT_COMPRESS, + TransportSettings.PING_SCHEDULE, + TransportSettings.CONNECT_TIMEOUT, + TransportSettings.DEFAULT_FEATURES_SETTING, + TransportSettings.TCP_NO_DELAY, + TransportSettings.TCP_NO_DELAY_PROFILE, + TransportSettings.TCP_KEEP_ALIVE, + TransportSettings.TCP_KEEP_ALIVE_PROFILE, + TransportSettings.TCP_REUSE_ADDRESS, + TransportSettings.TCP_REUSE_ADDRESS_PROFILE, + TransportSettings.TCP_SEND_BUFFER_SIZE, + TransportSettings.TCP_SEND_BUFFER_SIZE_PROFILE, + TransportSettings.TCP_RECEIVE_BUFFER_SIZE, + TransportSettings.TCP_RECEIVE_BUFFER_SIZE_PROFILE, + TransportSettings.CONNECTIONS_PER_NODE_RECOVERY, + TransportSettings.CONNECTIONS_PER_NODE_BULK, + TransportSettings.CONNECTIONS_PER_NODE_REG, + TransportSettings.CONNECTIONS_PER_NODE_STATE, + TransportSettings.CONNECTIONS_PER_NODE_PING, + TransportSettings.TRACE_LOG_EXCLUDE_SETTING, + TransportSettings.TRACE_LOG_INCLUDE_SETTING, + NetworkService.NETWORK_SERVER, + NetworkService.GLOBAL_NETWORK_HOST_SETTING, + NetworkService.GLOBAL_NETWORK_BIND_HOST_SETTING, + NetworkService.GLOBAL_NETWORK_PUBLISH_HOST_SETTING, + NetworkService.TCP_NO_DELAY, + NetworkService.TCP_KEEP_ALIVE, + NetworkService.TCP_REUSE_ADDRESS, + NetworkService.TCP_SEND_BUFFER_SIZE, + NetworkService.TCP_RECEIVE_BUFFER_SIZE, + IndexSettings.QUERY_STRING_ANALYZE_WILDCARD, + IndexSettings.QUERY_STRING_ALLOW_LEADING_WILDCARD, + ScriptService.SCRIPT_CACHE_SIZE_SETTING, + ScriptService.SCRIPT_CACHE_EXPIRE_SETTING, + ScriptService.SCRIPT_MAX_SIZE_IN_BYTES, + ScriptService.SCRIPT_MAX_COMPILATIONS_RATE, + ScriptService.TYPES_ALLOWED_SETTING, + ScriptService.CONTEXTS_ALLOWED_SETTING, + IndicesService.INDICES_CACHE_CLEAN_INTERVAL_SETTING, + IndicesFieldDataCache.INDICES_FIELDDATA_CACHE_SIZE_KEY, + IndicesRequestCache.INDICES_CACHE_QUERY_SIZE, + IndicesRequestCache.INDICES_CACHE_QUERY_EXPIRE, + HunspellService.HUNSPELL_LAZY_LOAD, + HunspellService.HUNSPELL_IGNORE_CASE, + HunspellService.HUNSPELL_DICTIONARY_OPTIONS, + IndicesStore.INDICES_STORE_DELETE_SHARD_TIMEOUT, + Environment.PATH_DATA_SETTING, + Environment.PATH_HOME_SETTING, + Environment.PATH_LOGS_SETTING, + Environment.PATH_REPO_SETTING, + Environment.PATH_SHARED_DATA_SETTING, + Environment.PIDFILE_SETTING, + NodeEnvironment.NODE_ID_SEED_SETTING, + Node.INITIAL_STATE_TIMEOUT_SETTING, + DiscoveryModule.DISCOVERY_TYPE_SETTING, + DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING, + SettingsBasedSeedHostsProvider.DISCOVERY_SEED_HOSTS_SETTING, + SeedHostsResolver.DISCOVERY_SEED_RESOLVER_MAX_CONCURRENT_RESOLVERS_SETTING, + SeedHostsResolver.DISCOVERY_SEED_RESOLVER_TIMEOUT_SETTING, + SearchService.DEFAULT_KEEPALIVE_SETTING, + SearchService.KEEPALIVE_INTERVAL_SETTING, + SearchService.MAX_KEEPALIVE_SETTING, + MultiBucketConsumerService.MAX_BUCKET_SETTING, + SearchService.LOW_LEVEL_CANCELLATION_SETTING, + SearchService.MAX_OPEN_SCROLL_CONTEXT, + Node.WRITE_PORTS_FILE_SETTING, + Node.NODE_NAME_SETTING, + Node.NODE_DATA_SETTING, + Node.NODE_MASTER_SETTING, + Node.NODE_INGEST_SETTING, + Node.NODE_ATTRIBUTES, + Node.NODE_LOCAL_STORAGE_SETTING, + AutoCreateIndex.AUTO_CREATE_INDEX_SETTING, + BaseRestHandler.MULTI_ALLOW_EXPLICIT_INDEX, + ClusterName.CLUSTER_NAME_SETTING, + Client.CLIENT_TYPE_SETTING_S, + ClusterModule.SHARDS_ALLOCATOR_TYPE_SETTING, + EsExecutors.PROCESSORS_SETTING, + ThreadContext.DEFAULT_HEADERS_SETTING, + Loggers.LOG_DEFAULT_LEVEL_SETTING, + Loggers.LOG_LEVEL_SETTING, + NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING, + NodeEnvironment.ENABLE_LUCENE_SEGMENT_INFOS_TRACE_SETTING, + OsService.REFRESH_INTERVAL_SETTING, + ProcessService.REFRESH_INTERVAL_SETTING, + JvmService.REFRESH_INTERVAL_SETTING, + FsService.REFRESH_INTERVAL_SETTING, + JvmGcMonitorService.ENABLED_SETTING, + JvmGcMonitorService.REFRESH_INTERVAL_SETTING, + JvmGcMonitorService.GC_SETTING, + JvmGcMonitorService.GC_OVERHEAD_WARN_SETTING, + JvmGcMonitorService.GC_OVERHEAD_INFO_SETTING, + JvmGcMonitorService.GC_OVERHEAD_DEBUG_SETTING, + PageCacheRecycler.LIMIT_HEAP_SETTING, + PageCacheRecycler.WEIGHT_BYTES_SETTING, + PageCacheRecycler.WEIGHT_INT_SETTING, + PageCacheRecycler.WEIGHT_LONG_SETTING, + PageCacheRecycler.WEIGHT_OBJECTS_SETTING, + PageCacheRecycler.TYPE_SETTING, + PluginsService.MANDATORY_SETTING, + BootstrapSettings.SECURITY_FILTER_BAD_DEFAULTS_SETTING, + BootstrapSettings.MEMORY_LOCK_SETTING, + BootstrapSettings.SYSTEM_CALL_FILTER_SETTING, + BootstrapSettings.CTRLHANDLER_SETTING, + KeyStoreWrapper.SEED_SETTING, + IndexingMemoryController.INDEX_BUFFER_SIZE_SETTING, + IndexingMemoryController.MIN_INDEX_BUFFER_SIZE_SETTING, + IndexingMemoryController.MAX_INDEX_BUFFER_SIZE_SETTING, + IndexingMemoryController.SHARD_INACTIVE_TIME_SETTING, + IndexingMemoryController.SHARD_MEMORY_INTERVAL_TIME_SETTING, + ResourceWatcherService.ENABLED, + ResourceWatcherService.RELOAD_INTERVAL_HIGH, + ResourceWatcherService.RELOAD_INTERVAL_MEDIUM, + ResourceWatcherService.RELOAD_INTERVAL_LOW, + SearchModule.INDICES_MAX_CLAUSE_COUNT_SETTING, + ThreadPool.ESTIMATED_TIME_INTERVAL_SETTING, + FastVectorHighlighter.SETTING_TV_HIGHLIGHT_MULTI_VALUE, + Node.BREAKER_TYPE_KEY, + OperationRouting.USE_ADAPTIVE_REPLICA_SELECTION_SETTING, + IndexGraveyard.SETTING_MAX_TOMBSTONES, + PersistentTasksClusterService.CLUSTER_TASKS_ALLOCATION_RECHECK_INTERVAL_SETTING, + EnableAssignmentDecider.CLUSTER_TASKS_ALLOCATION_ENABLE_SETTING, + PeerFinder.DISCOVERY_FIND_PEERS_INTERVAL_SETTING, + PeerFinder.DISCOVERY_REQUEST_PEERS_TIMEOUT_SETTING, + ClusterFormationFailureHelper.DISCOVERY_CLUSTER_FORMATION_WARNING_TIMEOUT_SETTING, + ElectionSchedulerFactory.ELECTION_INITIAL_TIMEOUT_SETTING, + ElectionSchedulerFactory.ELECTION_BACK_OFF_TIME_SETTING, + ElectionSchedulerFactory.ELECTION_MAX_TIMEOUT_SETTING, + ElectionSchedulerFactory.ELECTION_DURATION_SETTING, + Coordinator.PUBLISH_TIMEOUT_SETTING, + JoinHelper.JOIN_TIMEOUT_SETTING, + FollowersChecker.FOLLOWER_CHECK_TIMEOUT_SETTING, + FollowersChecker.FOLLOWER_CHECK_INTERVAL_SETTING, + FollowersChecker.FOLLOWER_CHECK_RETRY_COUNT_SETTING, + LeaderChecker.LEADER_CHECK_TIMEOUT_SETTING, + LeaderChecker.LEADER_CHECK_INTERVAL_SETTING, + LeaderChecker.LEADER_CHECK_RETRY_COUNT_SETTING, + Reconfigurator.CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION, + TransportAddVotingConfigExclusionsAction.MAXIMUM_VOTING_CONFIG_EXCLUSIONS_SETTING, + ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING, + ClusterBootstrapService.UNCONFIGURED_BOOTSTRAP_TIMEOUT_SETTING, + LagDetector.CLUSTER_FOLLOWER_LAG_TIMEOUT_SETTING); - public static List> BUILT_IN_SETTING_UPGRADERS = Collections.unmodifiableList(Arrays.asList( + static List> BUILT_IN_SETTING_UPGRADERS = List.of( RemoteClusterAware.SEARCH_REMOTE_CLUSTER_SEEDS_UPGRADER, RemoteClusterAware.SEARCH_REMOTE_CLUSTERS_PROXY_UPGRADER, - RemoteClusterService.SEARCH_REMOTE_CLUSTER_SKIP_UNAVAILABLE_UPGRADER)); + RemoteClusterService.SEARCH_REMOTE_CLUSTER_SKIP_UNAVAILABLE_UPGRADER); } diff --git a/server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java b/server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java index bbb824a497998..2acbbec3f8171 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java +++ b/server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java @@ -42,9 +42,7 @@ import org.elasticsearch.index.store.Store; import org.elasticsearch.indices.IndicesRequestCache; -import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Predicate; @@ -57,128 +55,129 @@ public final class IndexScopedSettings extends AbstractScopedSettings { public static final Predicate INDEX_SETTINGS_KEY_PREDICATE = (s) -> s.startsWith(IndexMetaData.INDEX_SETTING_PREFIX); - public static final Set> BUILT_IN_INDEX_SETTINGS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY, - MergeSchedulerConfig.AUTO_THROTTLE_SETTING, - MergeSchedulerConfig.MAX_MERGE_COUNT_SETTING, - MergeSchedulerConfig.MAX_THREAD_COUNT_SETTING, - IndexMetaData.SETTING_INDEX_VERSION_CREATED, - IndexMetaData.INDEX_ROUTING_EXCLUDE_GROUP_SETTING, - IndexMetaData.INDEX_ROUTING_INCLUDE_GROUP_SETTING, - IndexMetaData.INDEX_ROUTING_REQUIRE_GROUP_SETTING, - IndexMetaData.INDEX_AUTO_EXPAND_REPLICAS_SETTING, - IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING, - IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING, - IndexMetaData.INDEX_ROUTING_PARTITION_SIZE_SETTING, - IndexMetaData.INDEX_NUMBER_OF_ROUTING_SHARDS_SETTING, - IndexMetaData.INDEX_READ_ONLY_SETTING, - IndexMetaData.INDEX_BLOCKS_READ_SETTING, - IndexMetaData.INDEX_BLOCKS_WRITE_SETTING, - IndexMetaData.INDEX_BLOCKS_METADATA_SETTING, - IndexMetaData.INDEX_BLOCKS_READ_ONLY_ALLOW_DELETE_SETTING, - IndexMetaData.INDEX_PRIORITY_SETTING, - IndexMetaData.INDEX_DATA_PATH_SETTING, - IndexMetaData.INDEX_FORMAT_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING, - SearchSlowLog.INDEX_SEARCH_SLOWLOG_LEVEL, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING, - IndexingSlowLog.INDEX_INDEXING_SLOWLOG_MAX_SOURCE_CHARS_TO_LOG_SETTING, - MergePolicyConfig.INDEX_COMPOUND_FORMAT_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING, - MergePolicyConfig.INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT_SETTING, - IndexSortConfig.INDEX_SORT_FIELD_SETTING, - IndexSortConfig.INDEX_SORT_ORDER_SETTING, - IndexSortConfig.INDEX_SORT_MISSING_SETTING, - IndexSortConfig.INDEX_SORT_MODE_SETTING, - IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING, - IndexSettings.INDEX_WARMER_ENABLED_SETTING, - IndexSettings.INDEX_REFRESH_INTERVAL_SETTING, - IndexSettings.MAX_RESULT_WINDOW_SETTING, - IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING, - IndexSettings.MAX_TOKEN_COUNT_SETTING, - IndexSettings.MAX_DOCVALUE_FIELDS_SEARCH_SETTING, - IndexSettings.MAX_SCRIPT_FIELDS_SETTING, - IndexSettings.MAX_NGRAM_DIFF_SETTING, - IndexSettings.MAX_SHINGLE_DIFF_SETTING, - IndexSettings.MAX_RESCORE_WINDOW_SETTING, - IndexSettings.MAX_ADJACENCY_MATRIX_FILTERS_SETTING, - IndexSettings.MAX_ANALYZED_OFFSET_SETTING, - IndexSettings.MAX_TERMS_COUNT_SETTING, - IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING, - IndexSettings.DEFAULT_FIELD_SETTING, - IndexSettings.QUERY_STRING_LENIENT_SETTING, - IndexSettings.ALLOW_UNMAPPED, - IndexSettings.INDEX_CHECK_ON_STARTUP, - IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD, - IndexSettings.MAX_SLICES_PER_SCROLL, - IndexSettings.MAX_REGEX_LENGTH_SETTING, - ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING, - IndexSettings.INDEX_GC_DELETES_SETTING, - IndexSettings.INDEX_SOFT_DELETES_SETTING, - IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING, - IndexSettings.INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING, - IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING, - UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, - EnableAllocationDecider.INDEX_ROUTING_REBALANCE_ENABLE_SETTING, - EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING, - IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING, - IndexSettings.INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING, - IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING, - IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING, - IndexSettings.INDEX_SEARCH_IDLE_AFTER, - IndexSettings.INDEX_SEARCH_THROTTLED, - IndexFieldDataService.INDEX_FIELDDATA_CACHE_KEY, - FieldMapper.IGNORE_MALFORMED_SETTING, - FieldMapper.COERCE_SETTING, - Store.INDEX_STORE_STATS_REFRESH_INTERVAL_SETTING, - MapperService.INDEX_MAPPER_DYNAMIC_SETTING, - MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING, - MapperService.INDEX_MAPPING_NESTED_DOCS_LIMIT_SETTING, - MapperService.INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING, - MapperService.INDEX_MAPPING_DEPTH_LIMIT_SETTING, - MapperService.INDEX_MAPPING_FIELD_NAME_LENGTH_LIMIT_SETTING, - BitsetFilterCache.INDEX_LOAD_RANDOM_ACCESS_FILTERS_EAGERLY_SETTING, - IndexModule.INDEX_STORE_TYPE_SETTING, - IndexModule.INDEX_STORE_PRE_LOAD_SETTING, - IndexModule.INDEX_QUERY_CACHE_ENABLED_SETTING, - FsDirectoryService.INDEX_LOCK_FACTOR_SETTING, - Store.FORCE_RAM_TERM_DICT, - EngineConfig.INDEX_CODEC_SETTING, - IndexMetaData.SETTING_WAIT_FOR_ACTIVE_SHARDS, - IndexSettings.DEFAULT_PIPELINE, - MetaDataIndexStateService.VERIFIED_BEFORE_CLOSE_SETTING, + public static final Set> BUILT_IN_INDEX_SETTINGS = Set.of( + MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY, + MergeSchedulerConfig.AUTO_THROTTLE_SETTING, + MergeSchedulerConfig.MAX_MERGE_COUNT_SETTING, + MergeSchedulerConfig.MAX_THREAD_COUNT_SETTING, + IndexMetaData.SETTING_INDEX_VERSION_CREATED, + IndexMetaData.INDEX_ROUTING_EXCLUDE_GROUP_SETTING, + IndexMetaData.INDEX_ROUTING_INCLUDE_GROUP_SETTING, + IndexMetaData.INDEX_ROUTING_REQUIRE_GROUP_SETTING, + IndexMetaData.INDEX_AUTO_EXPAND_REPLICAS_SETTING, + IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING, + IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING, + IndexMetaData.INDEX_ROUTING_PARTITION_SIZE_SETTING, + IndexMetaData.INDEX_NUMBER_OF_ROUTING_SHARDS_SETTING, + IndexMetaData.INDEX_READ_ONLY_SETTING, + IndexMetaData.INDEX_BLOCKS_READ_SETTING, + IndexMetaData.INDEX_BLOCKS_WRITE_SETTING, + IndexMetaData.INDEX_BLOCKS_METADATA_SETTING, + IndexMetaData.INDEX_BLOCKS_READ_ONLY_ALLOW_DELETE_SETTING, + IndexMetaData.INDEX_PRIORITY_SETTING, + IndexMetaData.INDEX_DATA_PATH_SETTING, + IndexMetaData.INDEX_FORMAT_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_LEVEL, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_MAX_SOURCE_CHARS_TO_LOG_SETTING, + MergePolicyConfig.INDEX_COMPOUND_FORMAT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT_SETTING, + IndexSortConfig.INDEX_SORT_FIELD_SETTING, + IndexSortConfig.INDEX_SORT_ORDER_SETTING, + IndexSortConfig.INDEX_SORT_MISSING_SETTING, + IndexSortConfig.INDEX_SORT_MODE_SETTING, + IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING, + IndexSettings.INDEX_WARMER_ENABLED_SETTING, + IndexSettings.INDEX_REFRESH_INTERVAL_SETTING, + IndexSettings.MAX_RESULT_WINDOW_SETTING, + IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING, + IndexSettings.MAX_TOKEN_COUNT_SETTING, + IndexSettings.MAX_DOCVALUE_FIELDS_SEARCH_SETTING, + IndexSettings.MAX_SCRIPT_FIELDS_SETTING, + IndexSettings.MAX_NGRAM_DIFF_SETTING, + IndexSettings.MAX_SHINGLE_DIFF_SETTING, + IndexSettings.MAX_RESCORE_WINDOW_SETTING, + IndexSettings.MAX_ADJACENCY_MATRIX_FILTERS_SETTING, + IndexSettings.MAX_ANALYZED_OFFSET_SETTING, + IndexSettings.MAX_TERMS_COUNT_SETTING, + IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING, + IndexSettings.DEFAULT_FIELD_SETTING, + IndexSettings.QUERY_STRING_LENIENT_SETTING, + IndexSettings.ALLOW_UNMAPPED, + IndexSettings.INDEX_CHECK_ON_STARTUP, + IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD, + IndexSettings.MAX_SLICES_PER_SCROLL, + IndexSettings.MAX_REGEX_LENGTH_SETTING, + ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING, + IndexSettings.INDEX_GC_DELETES_SETTING, + IndexSettings.INDEX_SOFT_DELETES_SETTING, + IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING, + IndexSettings.INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING, + IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING, + UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, + EnableAllocationDecider.INDEX_ROUTING_REBALANCE_ENABLE_SETTING, + EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING, + IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING, + IndexSettings.INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING, + IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING, + IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING, + IndexSettings.INDEX_SEARCH_IDLE_AFTER, + IndexSettings.INDEX_SEARCH_THROTTLED, + IndexFieldDataService.INDEX_FIELDDATA_CACHE_KEY, + FieldMapper.IGNORE_MALFORMED_SETTING, + FieldMapper.COERCE_SETTING, + Store.INDEX_STORE_STATS_REFRESH_INTERVAL_SETTING, + MapperService.INDEX_MAPPER_DYNAMIC_SETTING, + MapperService.INDEX_MAPPING_NESTED_FIELDS_LIMIT_SETTING, + MapperService.INDEX_MAPPING_NESTED_DOCS_LIMIT_SETTING, + MapperService.INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING, + MapperService.INDEX_MAPPING_DEPTH_LIMIT_SETTING, + MapperService.INDEX_MAPPING_FIELD_NAME_LENGTH_LIMIT_SETTING, + BitsetFilterCache.INDEX_LOAD_RANDOM_ACCESS_FILTERS_EAGERLY_SETTING, + IndexModule.INDEX_STORE_TYPE_SETTING, + IndexModule.INDEX_STORE_PRE_LOAD_SETTING, + IndexModule.INDEX_QUERY_CACHE_ENABLED_SETTING, + FsDirectoryService.INDEX_LOCK_FACTOR_SETTING, + Store.FORCE_RAM_TERM_DICT, + EngineConfig.INDEX_CODEC_SETTING, + IndexMetaData.SETTING_WAIT_FOR_ACTIVE_SHARDS, + IndexSettings.DEFAULT_PIPELINE, + MetaDataIndexStateService.VERIFIED_BEFORE_CLOSE_SETTING, - // validate that built-in similarities don't get redefined - Setting.groupSetting("index.similarity.", (s) -> { - Map groups = s.getAsGroups(); - for (String key : SimilarityService.BUILT_IN.keySet()) { - if (groups.containsKey(key)) { - throw new IllegalArgumentException("illegal value for [index.similarity." + key + - "] cannot redefine built-in similarity"); - } - } - }, Property.IndexScope), // this allows similarity settings to be passed - Setting.groupSetting("index.analysis.", Property.IndexScope) // this allows analysis settings to be passed - - ))); + // validate that built-in similarities don't get redefined + Setting.groupSetting( + "index.similarity.", + (s) -> { + Map groups = s.getAsGroups(); + for (String key : SimilarityService.BUILT_IN.keySet()) { + if (groups.containsKey(key)) { + throw new IllegalArgumentException("illegal value for [index.similarity." + key + + "] cannot redefine built-in similarity"); + } + } + }, + Property.IndexScope), // this allows similarity settings to be passed + Setting.groupSetting("index.analysis.", Property.IndexScope)); // this allows analysis settings to be passed public static final IndexScopedSettings DEFAULT_SCOPED_SETTINGS = new IndexScopedSettings(Settings.EMPTY, BUILT_IN_INDEX_SETTINGS); diff --git a/server/src/main/java/org/elasticsearch/common/settings/Setting.java b/server/src/main/java/org/elasticsearch/common/settings/Setting.java index 9c3762f857e4a..514cfd3ce4ca8 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/Setting.java +++ b/server/src/main/java/org/elasticsearch/common/settings/Setting.java @@ -45,7 +45,6 @@ import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; -import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; @@ -650,7 +649,7 @@ public AffixSetting(AffixKey key, Setting delegate, Function(Arrays.asList(dependencies))); + this.dependencies = Set.of(dependencies); } boolean isGroupSetting() { diff --git a/server/src/main/java/org/elasticsearch/common/settings/Settings.java b/server/src/main/java/org/elasticsearch/common/settings/Settings.java index 3a7d719105afe..5789abf76d8b0 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/Settings.java +++ b/server/src/main/java/org/elasticsearch/common/settings/Settings.java @@ -57,7 +57,6 @@ 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; @@ -674,7 +673,7 @@ private static void validateValue(String key, Object currentValue, XContentParse public static final Set FORMAT_PARAMS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList("settings_filter", "flat_settings"))); + Set.of("settings_filter", "flat_settings"); /** * Returns {@code true} if this settings object contains no settings diff --git a/server/src/main/java/org/elasticsearch/common/settings/SettingsFilter.java b/server/src/main/java/org/elasticsearch/common/settings/SettingsFilter.java index 549713fd15261..588905f54d969 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/SettingsFilter.java +++ b/server/src/main/java/org/elasticsearch/common/settings/SettingsFilter.java @@ -26,8 +26,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Set; @@ -50,7 +48,7 @@ public SettingsFilter(Collection patterns) { throw new IllegalArgumentException("invalid pattern: " + pattern); } } - this.patterns = Collections.unmodifiableSet(new HashSet<>(patterns)); + this.patterns = Set.copyOf(patterns); patternString = Strings.collectionToDelimitedString(patterns, ","); } diff --git a/server/src/main/java/org/elasticsearch/common/time/DateUtils.java b/server/src/main/java/org/elasticsearch/common/time/DateUtils.java index e6bf6a65105b7..729cee7a6852c 100644 --- a/server/src/main/java/org/elasticsearch/common/time/DateUtils.java +++ b/server/src/main/java/org/elasticsearch/common/time/DateUtils.java @@ -34,6 +34,7 @@ import java.util.Map; import java.util.Set; +import static java.util.Map.entry; import static org.elasticsearch.common.time.DateUtilsRounding.getMonthOfYear; import static org.elasticsearch.common.time.DateUtilsRounding.getTotalMillisByYearMonth; import static org.elasticsearch.common.time.DateUtilsRounding.getYear; @@ -67,125 +68,121 @@ public static DateTimeZone zoneIdToDateTimeZone(ZoneId zoneId) { } // Map of deprecated timezones and their recommended new counterpart - public static final Map DEPRECATED_LONG_TIMEZONES; - static { - Map tzs = new HashMap<>(); - tzs.put("Africa/Asmera","Africa/Nairobi"); - tzs.put("Africa/Timbuktu","Africa/Abidjan"); - tzs.put("America/Argentina/ComodRivadavia","America/Argentina/Catamarca"); - tzs.put("America/Atka","America/Adak"); - tzs.put("America/Buenos_Aires","America/Argentina/Buenos_Aires"); - tzs.put("America/Catamarca","America/Argentina/Catamarca"); - tzs.put("America/Coral_Harbour","America/Atikokan"); - tzs.put("America/Cordoba","America/Argentina/Cordoba"); - tzs.put("America/Ensenada","America/Tijuana"); - tzs.put("America/Fort_Wayne","America/Indiana/Indianapolis"); - tzs.put("America/Indianapolis","America/Indiana/Indianapolis"); - tzs.put("America/Jujuy","America/Argentina/Jujuy"); - tzs.put("America/Knox_IN","America/Indiana/Knox"); - tzs.put("America/Louisville","America/Kentucky/Louisville"); - tzs.put("America/Mendoza","America/Argentina/Mendoza"); - tzs.put("America/Montreal","America/Toronto"); - tzs.put("America/Porto_Acre","America/Rio_Branco"); - tzs.put("America/Rosario","America/Argentina/Cordoba"); - tzs.put("America/Santa_Isabel","America/Tijuana"); - tzs.put("America/Shiprock","America/Denver"); - tzs.put("America/Virgin","America/Port_of_Spain"); - tzs.put("Antarctica/South_Pole","Pacific/Auckland"); - tzs.put("Asia/Ashkhabad","Asia/Ashgabat"); - tzs.put("Asia/Calcutta","Asia/Kolkata"); - tzs.put("Asia/Chongqing","Asia/Shanghai"); - tzs.put("Asia/Chungking","Asia/Shanghai"); - tzs.put("Asia/Dacca","Asia/Dhaka"); - tzs.put("Asia/Harbin","Asia/Shanghai"); - tzs.put("Asia/Kashgar","Asia/Urumqi"); - tzs.put("Asia/Katmandu","Asia/Kathmandu"); - tzs.put("Asia/Macao","Asia/Macau"); - tzs.put("Asia/Rangoon","Asia/Yangon"); - tzs.put("Asia/Saigon","Asia/Ho_Chi_Minh"); - tzs.put("Asia/Tel_Aviv","Asia/Jerusalem"); - tzs.put("Asia/Thimbu","Asia/Thimphu"); - tzs.put("Asia/Ujung_Pandang","Asia/Makassar"); - tzs.put("Asia/Ulan_Bator","Asia/Ulaanbaatar"); - tzs.put("Atlantic/Faeroe","Atlantic/Faroe"); - tzs.put("Atlantic/Jan_Mayen","Europe/Oslo"); - tzs.put("Australia/ACT","Australia/Sydney"); - tzs.put("Australia/Canberra","Australia/Sydney"); - tzs.put("Australia/LHI","Australia/Lord_Howe"); - tzs.put("Australia/NSW","Australia/Sydney"); - tzs.put("Australia/North","Australia/Darwin"); - tzs.put("Australia/Queensland","Australia/Brisbane"); - tzs.put("Australia/South","Australia/Adelaide"); - tzs.put("Australia/Tasmania","Australia/Hobart"); - tzs.put("Australia/Victoria","Australia/Melbourne"); - tzs.put("Australia/West","Australia/Perth"); - tzs.put("Australia/Yancowinna","Australia/Broken_Hill"); - tzs.put("Brazil/Acre","America/Rio_Branco"); - tzs.put("Brazil/DeNoronha","America/Noronha"); - tzs.put("Brazil/East","America/Sao_Paulo"); - tzs.put("Brazil/West","America/Manaus"); - tzs.put("Canada/Atlantic","America/Halifax"); - tzs.put("Canada/Central","America/Winnipeg"); - tzs.put("Canada/East-Saskatchewan","America/Regina"); - tzs.put("Canada/Eastern","America/Toronto"); - tzs.put("Canada/Mountain","America/Edmonton"); - tzs.put("Canada/Newfoundland","America/St_Johns"); - tzs.put("Canada/Pacific","America/Vancouver"); - tzs.put("Canada/Yukon","America/Whitehorse"); - tzs.put("Chile/Continental","America/Santiago"); - tzs.put("Chile/EasterIsland","Pacific/Easter"); - tzs.put("Cuba","America/Havana"); - tzs.put("Egypt","Africa/Cairo"); - tzs.put("Eire","Europe/Dublin"); - tzs.put("Europe/Belfast","Europe/London"); - tzs.put("Europe/Tiraspol","Europe/Chisinau"); - tzs.put("GB","Europe/London"); - tzs.put("GB-Eire","Europe/London"); - tzs.put("Greenwich","Etc/GMT"); - tzs.put("Hongkong","Asia/Hong_Kong"); - tzs.put("Iceland","Atlantic/Reykjavik"); - tzs.put("Iran","Asia/Tehran"); - tzs.put("Israel","Asia/Jerusalem"); - tzs.put("Jamaica","America/Jamaica"); - tzs.put("Japan","Asia/Tokyo"); - tzs.put("Kwajalein","Pacific/Kwajalein"); - tzs.put("Libya","Africa/Tripoli"); - tzs.put("Mexico/BajaNorte","America/Tijuana"); - tzs.put("Mexico/BajaSur","America/Mazatlan"); - tzs.put("Mexico/General","America/Mexico_City"); - tzs.put("NZ","Pacific/Auckland"); - tzs.put("NZ-CHAT","Pacific/Chatham"); - tzs.put("Navajo","America/Denver"); - tzs.put("PRC","Asia/Shanghai"); - tzs.put("Pacific/Johnston","Pacific/Honolulu"); - tzs.put("Pacific/Ponape","Pacific/Pohnpei"); - tzs.put("Pacific/Samoa","Pacific/Pago_Pago"); - tzs.put("Pacific/Truk","Pacific/Chuuk"); - tzs.put("Pacific/Yap","Pacific/Chuuk"); - tzs.put("Poland","Europe/Warsaw"); - tzs.put("Portugal","Europe/Lisbon"); - tzs.put("ROC","Asia/Taipei"); - tzs.put("ROK","Asia/Seoul"); - tzs.put("Singapore","Asia/Singapore"); - tzs.put("Turkey","Europe/Istanbul"); - tzs.put("UCT","Etc/UCT"); - tzs.put("US/Alaska","America/Anchorage"); - tzs.put("US/Aleutian","America/Adak"); - tzs.put("US/Arizona","America/Phoenix"); - tzs.put("US/Central","America/Chicago"); - tzs.put("US/East-Indiana","America/Indiana/Indianapolis"); - tzs.put("US/Eastern","America/New_York"); - tzs.put("US/Hawaii","Pacific/Honolulu"); - tzs.put("US/Indiana-Starke","America/Indiana/Knox"); - tzs.put("US/Michigan","America/Detroit"); - tzs.put("US/Mountain","America/Denver"); - tzs.put("US/Pacific","America/Los_Angeles"); - tzs.put("US/Samoa","Pacific/Pago_Pago"); - tzs.put("Universal","Etc/UTC"); - tzs.put("W-SU","Europe/Moscow"); - tzs.put("Zulu","Etc/UTC"); - DEPRECATED_LONG_TIMEZONES = Collections.unmodifiableMap(tzs); - } + public static final Map DEPRECATED_LONG_TIMEZONES = Map.ofEntries( + entry("Africa/Asmera", "Africa/Nairobi"), + entry("Africa/Timbuktu", "Africa/Abidjan"), + entry("America/Argentina/ComodRivadavia", "America/Argentina/Catamarca"), + entry("America/Atka", "America/Adak"), + entry("America/Buenos_Aires", "America/Argentina/Buenos_Aires"), + entry("America/Catamarca", "America/Argentina/Catamarca"), + entry("America/Coral_Harbour", "America/Atikokan"), + entry("America/Cordoba", "America/Argentina/Cordoba"), + entry("America/Ensenada", "America/Tijuana"), + entry("America/Fort_Wayne", "America/Indiana/Indianapolis"), + entry("America/Indianapolis", "America/Indiana/Indianapolis"), + entry("America/Jujuy", "America/Argentina/Jujuy"), + entry("America/Knox_IN", "America/Indiana/Knox"), + entry("America/Louisville", "America/Kentucky/Louisville"), + entry("America/Mendoza", "America/Argentina/Mendoza"), + entry("America/Montreal", "America/Toronto"), + entry("America/Porto_Acre", "America/Rio_Branco"), + entry("America/Rosario", "America/Argentina/Cordoba"), + entry("America/Santa_Isabel", "America/Tijuana"), + entry("America/Shiprock", "America/Denver"), + entry("America/Virgin", "America/Port_of_Spain"), + entry("Antarctica/South_Pole", "Pacific/Auckland"), + entry("Asia/Ashkhabad", "Asia/Ashgabat"), + entry("Asia/Calcutta", "Asia/Kolkata"), + entry("Asia/Chongqing", "Asia/Shanghai"), + entry("Asia/Chungking", "Asia/Shanghai"), + entry("Asia/Dacca", "Asia/Dhaka"), + entry("Asia/Harbin", "Asia/Shanghai"), + entry("Asia/Kashgar", "Asia/Urumqi"), + entry("Asia/Katmandu", "Asia/Kathmandu"), + entry("Asia/Macao", "Asia/Macau"), + entry("Asia/Rangoon", "Asia/Yangon"), + entry("Asia/Saigon", "Asia/Ho_Chi_Minh"), + entry("Asia/Tel_Aviv", "Asia/Jerusalem"), + entry("Asia/Thimbu", "Asia/Thimphu"), + entry("Asia/Ujung_Pandang", "Asia/Makassar"), + entry("Asia/Ulan_Bator", "Asia/Ulaanbaatar"), + entry("Atlantic/Faeroe", "Atlantic/Faroe"), + entry("Atlantic/Jan_Mayen", "Europe/Oslo"), + entry("Australia/ACT", "Australia/Sydney"), + entry("Australia/Canberra", "Australia/Sydney"), + entry("Australia/LHI", "Australia/Lord_Howe"), + entry("Australia/NSW", "Australia/Sydney"), + entry("Australia/North", "Australia/Darwin"), + entry("Australia/Queensland", "Australia/Brisbane"), + entry("Australia/South", "Australia/Adelaide"), + entry("Australia/Tasmania", "Australia/Hobart"), + entry("Australia/Victoria", "Australia/Melbourne"), + entry("Australia/West", "Australia/Perth"), + entry("Australia/Yancowinna", "Australia/Broken_Hill"), + entry("Brazil/Acre", "America/Rio_Branco"), + entry("Brazil/DeNoronha", "America/Noronha"), + entry("Brazil/East", "America/Sao_Paulo"), + entry("Brazil/West", "America/Manaus"), + entry("Canada/Atlantic", "America/Halifax"), + entry("Canada/Central", "America/Winnipeg"), + entry("Canada/East-Saskatchewan", "America/Regina"), + entry("Canada/Eastern", "America/Toronto"), + entry("Canada/Mountain", "America/Edmonton"), + entry("Canada/Newfoundland", "America/St_Johns"), + entry("Canada/Pacific", "America/Vancouver"), + entry("Canada/Yukon", "America/Whitehorse"), + entry("Chile/Continental", "America/Santiago"), + entry("Chile/EasterIsland", "Pacific/Easter"), + entry("Cuba", "America/Havana"), + entry("Egypt", "Africa/Cairo"), + entry("Eire", "Europe/Dublin"), + entry("Europe/Belfast", "Europe/London"), + entry("Europe/Tiraspol", "Europe/Chisinau"), + entry("GB", "Europe/London"), + entry("GB-Eire", "Europe/London"), + entry("Greenwich", "Etc/GMT"), + entry("Hongkong", "Asia/Hong_Kong"), + entry("Iceland", "Atlantic/Reykjavik"), + entry("Iran", "Asia/Tehran"), + entry("Israel", "Asia/Jerusalem"), + entry("Jamaica", "America/Jamaica"), + entry("Japan", "Asia/Tokyo"), + entry("Kwajalein", "Pacific/Kwajalein"), + entry("Libya", "Africa/Tripoli"), + entry("Mexico/BajaNorte", "America/Tijuana"), + entry("Mexico/BajaSur", "America/Mazatlan"), + entry("Mexico/General", "America/Mexico_City"), + entry("NZ", "Pacific/Auckland"), + entry("NZ-CHAT", "Pacific/Chatham"), + entry("Navajo", "America/Denver"), + entry("PRC", "Asia/Shanghai"), + entry("Pacific/Johnston", "Pacific/Honolulu"), + entry("Pacific/Ponape", "Pacific/Pohnpei"), + entry("Pacific/Samoa", "Pacific/Pago_Pago"), + entry("Pacific/Truk", "Pacific/Chuuk"), + entry("Pacific/Yap", "Pacific/Chuuk"), + entry("Poland", "Europe/Warsaw"), + entry("Portugal", "Europe/Lisbon"), + entry("ROC", "Asia/Taipei"), + entry("ROK", "Asia/Seoul"), + entry("Singapore", "Asia/Singapore"), + entry("Turkey", "Europe/Istanbul"), + entry("UCT", "Etc/UCT"), + entry("US/Alaska", "America/Anchorage"), + entry("US/Aleutian", "America/Adak"), + entry("US/Arizona", "America/Phoenix"), + entry("US/Central", "America/Chicago"), + entry("US/East-Indiana", "America/Indiana/Indianapolis"), + entry("US/Eastern", "America/New_York"), + entry("US/Hawaii", "Pacific/Honolulu"), + entry("US/Indiana-Starke", "America/Indiana/Knox"), + entry("US/Michigan", "America/Detroit"), + entry("US/Mountain", "America/Denver"), + entry("US/Pacific", "America/Los_Angeles"), + entry("US/Samoa", "Pacific/Pago_Pago"), + entry("Universal", "Etc/UTC"), + entry("W-SU", "Europe/Moscow"), + entry("Zulu", "Etc/UTC")); public static ZoneId dateTimeZoneToZoneId(DateTimeZone timeZone) { if (timeZone == null) { diff --git a/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java b/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java index 80a9a30032e17..b52bc2b199c80 100644 --- a/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java +++ b/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java @@ -34,7 +34,6 @@ import java.io.Closeable; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; @@ -277,7 +276,7 @@ public Map> getResponseHeaders() { HashMap> map = new HashMap<>(responseHeaders.size()); for (Map.Entry> entry : responseHeaders.entrySet()) { - map.put(entry.getKey(), Collections.unmodifiableList(new ArrayList<>(entry.getValue()))); + map.put(entry.getKey(), List.copyOf(entry.getValue())); } return Collections.unmodifiableMap(map); diff --git a/server/src/main/java/org/elasticsearch/env/NodeEnvironment.java b/server/src/main/java/org/elasticsearch/env/NodeEnvironment.java index f7e6f8e949b37..fc2f76d3436c0 100644 --- a/server/src/main/java/org/elasticsearch/env/NodeEnvironment.java +++ b/server/src/main/java/org/elasticsearch/env/NodeEnvironment.java @@ -85,8 +85,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static java.util.Collections.unmodifiableSet; - /** * A component that holds all data paths for a single node. */ @@ -693,7 +691,7 @@ public interface ShardLocker { */ public Set lockedShards() { synchronized (shardLocks) { - return unmodifiableSet(new HashSet<>(shardLocks.keySet())); + return Set.copyOf(shardLocks.keySet()); } } diff --git a/server/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java b/server/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java index 75654c077705f..d03f6abf7d9bd 100644 --- a/server/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java +++ b/server/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java @@ -46,7 +46,6 @@ import java.util.concurrent.atomic.AtomicLong; import static java.util.Collections.emptySet; -import static java.util.Collections.unmodifiableSet; /** * Allows to asynchronously fetch shard related data from other nodes for allocation, without blocking @@ -152,7 +151,7 @@ public synchronized FetchResult fetchData(DiscoveryNodes nodes, Set i } } } - Set allIgnoreNodes = unmodifiableSet(new HashSet<>(nodesToIgnore)); + Set allIgnoreNodes = Set.copyOf(nodesToIgnore); // clear the nodes to ignore, we had a successful run in fetching everything we can // we need to try them if another full run is needed nodesToIgnore.clear(); diff --git a/server/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java b/server/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java index 4d7949cdf4de8..9a1c79b476e1b 100644 --- a/server/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java +++ b/server/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java @@ -44,7 +44,6 @@ import java.util.stream.Collectors; import static java.util.Collections.emptyMap; -import static java.util.Collections.unmodifiableMap; /** * The dangling indices state is responsible for finding new dangling indices (indices that have @@ -88,7 +87,7 @@ public void processDanglingIndices(final MetaData metaData) { */ Map getDanglingIndices() { // This might be a good use case for CopyOnWriteHashMap - return unmodifiableMap(new HashMap<>(danglingIndices)); + return Map.copyOf(danglingIndices); } /** diff --git a/server/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java b/server/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java index d4e6362085238..e19cbe38c7e37 100644 --- a/server/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java +++ b/server/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java @@ -31,9 +31,7 @@ import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; /** @@ -50,7 +48,7 @@ final class CompositeIndexEventListener implements IndexEventListener { throw new IllegalArgumentException("listeners must be non-null"); } } - this.listeners = Collections.unmodifiableList(new ArrayList<>(listeners)); + this.listeners = List.copyOf(listeners); this.logger = Loggers.getLogger(getClass(), indexSettings.getIndex()); } diff --git a/server/src/main/java/org/elasticsearch/index/analysis/Analysis.java b/server/src/main/java/org/elasticsearch/index/analysis/Analysis.java index 09a87124110b3..303e7049306a7 100644 --- a/server/src/main/java/org/elasticsearch/index/analysis/Analysis.java +++ b/server/src/main/java/org/elasticsearch/index/analysis/Analysis.java @@ -69,13 +69,12 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import static java.util.Collections.unmodifiableMap; +import static java.util.Map.entry; public class Analysis { @@ -113,45 +112,40 @@ public static CharArraySet parseStemExclusion(Settings settings, CharArraySet de } } - public static final Map> NAMED_STOP_WORDS; - static { - Map> namedStopWords = new HashMap<>(); - namedStopWords.put("_arabic_", ArabicAnalyzer.getDefaultStopSet()); - namedStopWords.put("_armenian_", ArmenianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_basque_", BasqueAnalyzer.getDefaultStopSet()); - namedStopWords.put("_bengali_", BengaliAnalyzer.getDefaultStopSet()); - namedStopWords.put("_brazilian_", BrazilianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_bulgarian_", BulgarianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_catalan_", CatalanAnalyzer.getDefaultStopSet()); - namedStopWords.put("_czech_", CzechAnalyzer.getDefaultStopSet()); - namedStopWords.put("_danish_", DanishAnalyzer.getDefaultStopSet()); - namedStopWords.put("_dutch_", DutchAnalyzer.getDefaultStopSet()); - namedStopWords.put("_english_", EnglishAnalyzer.getDefaultStopSet()); - namedStopWords.put("_finnish_", FinnishAnalyzer.getDefaultStopSet()); - namedStopWords.put("_french_", FrenchAnalyzer.getDefaultStopSet()); - namedStopWords.put("_galician_", GalicianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_german_", GermanAnalyzer.getDefaultStopSet()); - namedStopWords.put("_greek_", GreekAnalyzer.getDefaultStopSet()); - namedStopWords.put("_hindi_", HindiAnalyzer.getDefaultStopSet()); - namedStopWords.put("_hungarian_", HungarianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_indonesian_", IndonesianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_irish_", IrishAnalyzer.getDefaultStopSet()); - namedStopWords.put("_italian_", ItalianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_latvian_", LatvianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_lithuanian_", LithuanianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_norwegian_", NorwegianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_persian_", PersianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_portuguese_", PortugueseAnalyzer.getDefaultStopSet()); - namedStopWords.put("_romanian_", RomanianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_russian_", RussianAnalyzer.getDefaultStopSet()); - namedStopWords.put("_sorani_", SoraniAnalyzer.getDefaultStopSet()); - namedStopWords.put("_spanish_", SpanishAnalyzer.getDefaultStopSet()); - namedStopWords.put("_swedish_", SwedishAnalyzer.getDefaultStopSet()); - namedStopWords.put("_thai_", ThaiAnalyzer.getDefaultStopSet()); - namedStopWords.put("_turkish_", TurkishAnalyzer.getDefaultStopSet()); - - NAMED_STOP_WORDS = unmodifiableMap(namedStopWords); - } + private static final Map> NAMED_STOP_WORDS = Map.ofEntries( + entry("_arabic_", ArabicAnalyzer.getDefaultStopSet()), + entry("_armenian_", ArmenianAnalyzer.getDefaultStopSet()), + entry("_basque_", BasqueAnalyzer.getDefaultStopSet()), + entry("_bengali_", BengaliAnalyzer.getDefaultStopSet()), + entry("_brazilian_", BrazilianAnalyzer.getDefaultStopSet()), + entry("_bulgarian_", BulgarianAnalyzer.getDefaultStopSet()), + entry("_catalan_", CatalanAnalyzer.getDefaultStopSet()), + entry("_czech_", CzechAnalyzer.getDefaultStopSet()), + entry("_danish_", DanishAnalyzer.getDefaultStopSet()), + entry("_dutch_", DutchAnalyzer.getDefaultStopSet()), + entry("_english_", EnglishAnalyzer.getDefaultStopSet()), + entry("_finnish_", FinnishAnalyzer.getDefaultStopSet()), + entry("_french_", FrenchAnalyzer.getDefaultStopSet()), + entry("_galician_", GalicianAnalyzer.getDefaultStopSet()), + entry("_german_", GermanAnalyzer.getDefaultStopSet()), + entry("_greek_", GreekAnalyzer.getDefaultStopSet()), + entry("_hindi_", HindiAnalyzer.getDefaultStopSet()), + entry("_hungarian_", HungarianAnalyzer.getDefaultStopSet()), + entry("_indonesian_", IndonesianAnalyzer.getDefaultStopSet()), + entry("_irish_", IrishAnalyzer.getDefaultStopSet()), + entry("_italian_", ItalianAnalyzer.getDefaultStopSet()), + entry("_latvian_", LatvianAnalyzer.getDefaultStopSet()), + entry("_lithuanian_", LithuanianAnalyzer.getDefaultStopSet()), + entry("_norwegian_", NorwegianAnalyzer.getDefaultStopSet()), + entry("_persian_", PersianAnalyzer.getDefaultStopSet()), + entry("_portuguese_", PortugueseAnalyzer.getDefaultStopSet()), + entry("_romanian_", RomanianAnalyzer.getDefaultStopSet()), + entry("_russian_", RussianAnalyzer.getDefaultStopSet()), + entry("_sorani_", SoraniAnalyzer.getDefaultStopSet()), + entry("_spanish_", SpanishAnalyzer.getDefaultStopSet()), + entry("_swedish_", SwedishAnalyzer.getDefaultStopSet()), + entry("_thai_", ThaiAnalyzer.getDefaultStopSet()), + entry("_turkish_", TurkishAnalyzer.getDefaultStopSet())); public static CharArraySet parseWords(Environment env, Settings settings, String name, CharArraySet defaultWords, Map> namedWords, boolean ignoreCase) { diff --git a/server/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java b/server/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java index c9e81ca4f2dc1..e90ba987b62ec 100644 --- a/server/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java +++ b/server/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java @@ -26,9 +26,7 @@ import org.apache.lucene.util.packed.PackedLongValues; import org.elasticsearch.index.fielddata.ordinals.Ordinals; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; public class PagedBytesAtomicFieldData extends AbstractAtomicOrdinalsFieldData { @@ -60,11 +58,10 @@ public long ramBytesUsed() { @Override public Collection getChildResources() { - List resources = new ArrayList<>(); - resources.add(Accountables.namedAccountable("ordinals", ordinals)); - resources.add(Accountables.namedAccountable("term bytes", bytes)); - resources.add(Accountables.namedAccountable("term offsets", termOrdToBytesOffset)); - return Collections.unmodifiableList(resources); + return List.of( + Accountables.namedAccountable("ordinals", ordinals), + Accountables.namedAccountable("term bytes", bytes), + Accountables.namedAccountable("term offsets", termOrdToBytesOffset)); } @Override diff --git a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java index 31a0f900db54f..f3ba3e13692f1 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java @@ -38,8 +38,6 @@ import java.util.Map; import java.util.function.Supplier; -import static java.util.Collections.unmodifiableMap; - public class DocumentMapperParser { final MapperService mapperService; @@ -130,7 +128,7 @@ private DocumentMapper parse(String type, Map mapping, String de if (meta != null) { // It may not be required to copy meta here to maintain immutability // but the cost is pretty low here. - docBuilder.meta(unmodifiableMap(new HashMap<>(meta))); + docBuilder.meta(Map.copyOf(meta)); } checkNoRemainingFields(mapping, parserContext.indexVersionCreated(), "Root mapping definition has unsupported parameters: "); diff --git a/server/src/main/java/org/elasticsearch/index/query/QueryShardContext.java b/server/src/main/java/org/elasticsearch/index/query/QueryShardContext.java index 2b5415115895d..0c33ee7102346 100644 --- a/server/src/main/java/org/elasticsearch/index/query/QueryShardContext.java +++ b/server/src/main/java/org/elasticsearch/index/query/QueryShardContext.java @@ -67,8 +67,6 @@ import java.util.function.BiFunction; import java.util.function.LongSupplier; -import static java.util.Collections.unmodifiableMap; - /** * Context object used to create lucene queries on the shard level. */ @@ -187,7 +185,7 @@ public void addNamedQuery(String name, Query query) { public Map copyNamedQueries() { // This might be a good use case for CopyOnWriteHashMap - return unmodifiableMap(new HashMap<>(namedQueries)); + return Map.copyOf(namedQueries); } /** diff --git a/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java b/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java index 04970a38bd99d..ecf958c21d17a 100644 --- a/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java +++ b/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java @@ -56,13 +56,10 @@ import org.elasticsearch.common.settings.Settings; import java.util.Arrays; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import static java.util.Collections.unmodifiableMap; - final class SimilarityProviders { private SimilarityProviders() {} // no instantiation @@ -70,60 +67,35 @@ private SimilarityProviders() {} // no instantiation private static final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger(SimilarityProviders.class)); static final String DISCOUNT_OVERLAPS = "discount_overlaps"; - private static final Map BASIC_MODELS; - private static final Map LEGACY_BASIC_MODELS; - private static final Map AFTER_EFFECTS; - private static final Map LEGACY_AFTER_EFFECTS; - - static { - Map models = new HashMap<>(); - models.put("g", new BasicModelG()); - models.put("if", new BasicModelIF()); - models.put("in", new BasicModelIn()); - models.put("ine", new BasicModelIne()); - BASIC_MODELS = unmodifiableMap(models); - - Map legacyModels = new HashMap<>(); - // TODO: be and g and both based on the bose-einstein model. - // Is there a better replacement for d and p which use the binomial model? - legacyModels.put("be", "g"); - legacyModels.put("d", "ine"); - legacyModels.put("p", "ine"); - LEGACY_BASIC_MODELS = unmodifiableMap(legacyModels); - - Map effects = new HashMap<>(); - effects.put("b", new AfterEffectB()); - effects.put("l", new AfterEffectL()); - AFTER_EFFECTS = unmodifiableMap(effects); - - Map legacyEffects = new HashMap<>(); - // l is simpler than b, so this should be a better replacement for "no" - legacyEffects.put("no", "l"); - LEGACY_AFTER_EFFECTS = unmodifiableMap(legacyEffects); - } - - private static final Map INDEPENDENCE_MEASURES; - static { - Map measures = new HashMap<>(); - measures.put("standardized", new IndependenceStandardized()); - measures.put("saturated", new IndependenceSaturated()); - measures.put("chisquared", new IndependenceChiSquared()); - INDEPENDENCE_MEASURES = unmodifiableMap(measures); - } + private static final Map BASIC_MODELS = Map.of( + "g", new BasicModelG(), + "if", new BasicModelIF(), + "in", new BasicModelIn(), + "ine", new BasicModelIne()); + // TODO: be and g and both based on the bose-einstein model. + // Is there a better replacement for d and p which use the binomial model? + private static final Map LEGACY_BASIC_MODELS = Map.of( + "be", "g", + "d", "ine", + "p", "ine"); + private static final Map AFTER_EFFECTS = Map.of( + "b", new AfterEffectB(), + "l", new AfterEffectL()); + // l is simpler than b, so this should be a better replacement for "no" + private static final Map LEGACY_AFTER_EFFECTS = Map.of("no", "l"); + + private static final Map INDEPENDENCE_MEASURES = Map.of( + "standardized", new IndependenceStandardized(), + "saturated", new IndependenceSaturated(), + "chisquared", new IndependenceChiSquared()); private static final Map DISTRIBUTIONS; private static final Map LAMBDAS; static { - Map distributions = new HashMap<>(); - distributions.put("ll", new DistributionLL()); - distributions.put("spl", new DistributionSPL()); - DISTRIBUTIONS = unmodifiableMap(distributions); - - Map lamdas = new HashMap<>(); - lamdas.put("df", new LambdaDF()); - lamdas.put("ttf", new LambdaTTF()); - LAMBDAS = unmodifiableMap(lamdas); + DISTRIBUTIONS = Map.of("ll", new DistributionLL(), "spl", new DistributionSPL()); + + LAMBDAS = Map.of("df", new LambdaDF(), "ttf", new LambdaTTF()); } /** diff --git a/server/src/main/java/org/elasticsearch/indices/flush/ShardsSyncedFlushResult.java b/server/src/main/java/org/elasticsearch/indices/flush/ShardsSyncedFlushResult.java index a2d9d5943261d..bd0451498c6ba 100644 --- a/server/src/main/java/org/elasticsearch/indices/flush/ShardsSyncedFlushResult.java +++ b/server/src/main/java/org/elasticsearch/indices/flush/ShardsSyncedFlushResult.java @@ -29,7 +29,6 @@ import java.util.Map; import static java.util.Collections.emptyMap; -import static java.util.Collections.unmodifiableMap; /** * Result for all copies of a shard @@ -68,7 +67,7 @@ public ShardsSyncedFlushResult(ShardId shardId, int totalShards, Map shardResponses) { this.failureReason = null; - this.shardResponses = unmodifiableMap(new HashMap<>(shardResponses)); + this.shardResponses = Map.copyOf(shardResponses); this.syncId = syncId; this.totalShards = totalShards; this.shardId = shardId; diff --git a/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java b/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java index 4d27362af22b5..7393eccc44e86 100644 --- a/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java +++ b/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java @@ -37,8 +37,6 @@ import org.elasticsearch.index.shard.ShardId; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -713,7 +711,7 @@ public synchronized void writeTo(StreamOutput out) throws IOException { } public synchronized List fileDetails() { - return Collections.unmodifiableList(new ArrayList<>(fileDetails.values())); + return List.copyOf(fileDetails.values()); } public synchronized void reset() { diff --git a/server/src/main/java/org/elasticsearch/ingest/ConditionalProcessor.java b/server/src/main/java/org/elasticsearch/ingest/ConditionalProcessor.java index d5d489ec0e626..e5333485db52b 100644 --- a/server/src/main/java/org/elasticsearch/ingest/ConditionalProcessor.java +++ b/server/src/main/java/org/elasticsearch/ingest/ConditionalProcessor.java @@ -19,11 +19,15 @@ package org.elasticsearch.ingest; +import org.elasticsearch.script.DeprecationMap; +import org.elasticsearch.script.IngestConditionalScript; +import org.elasticsearch.script.Script; +import org.elasticsearch.script.ScriptService; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; @@ -33,22 +37,10 @@ import java.util.function.LongSupplier; import java.util.stream.Collectors; -import org.elasticsearch.script.DeprecationMap; -import org.elasticsearch.script.IngestConditionalScript; -import org.elasticsearch.script.Script; -import org.elasticsearch.script.ScriptService; - public class ConditionalProcessor extends AbstractProcessor { - private static final Map DEPRECATIONS; - static { - Map deprecations = new HashMap<>(); - deprecations.put( - "_type", - "[types removal] Looking up doc types [_type] in scripts is deprecated." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + private static final Map DEPRECATIONS = + Map.of("_type", "[types removal] Looking up doc types [_type] in scripts is deprecated."); static final String TYPE = "conditional"; diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestNodesStatsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestNodesStatsAction.java index 14c8655e48c18..e74c42f3c396d 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestNodesStatsAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestNodesStatsAction.java @@ -39,6 +39,7 @@ import java.util.TreeSet; import java.util.function.Consumer; +import static java.util.Map.entry; import static org.elasticsearch.rest.RestRequest.Method.GET; public class RestNodesStatsAction extends BaseRestHandler { @@ -55,25 +56,20 @@ public RestNodesStatsAction(Settings settings, RestController controller) { controller.registerHandler(GET, "/_nodes/{nodeId}/stats/{metric}/{index_metric}", this); } - static final Map> METRICS; - - static { - final Map> metrics = new HashMap<>(); - metrics.put("os", r -> r.os(true)); - metrics.put("jvm", r -> r.jvm(true)); - metrics.put("thread_pool", r -> r.threadPool(true)); - metrics.put("fs", r -> r.fs(true)); - metrics.put("transport", r -> r.transport(true)); - metrics.put("http", r -> r.http(true)); - metrics.put("indices", r -> r.indices(true)); - metrics.put("process", r -> r.process(true)); - metrics.put("breaker", r -> r.breaker(true)); - metrics.put("script", r -> r.script(true)); - metrics.put("discovery", r -> r.discovery(true)); - metrics.put("ingest", r -> r.ingest(true)); - metrics.put("adaptive_selection", r -> r.adaptiveSelection(true)); - METRICS = Collections.unmodifiableMap(metrics); - } + static final Map> METRICS = Map.ofEntries( + entry("os", r -> r.os(true)), + entry("jvm", r -> r.jvm(true)), + entry("thread_pool", r -> r.threadPool(true)), + entry("fs", r -> r.fs(true)), + entry("transport", r -> r.transport(true)), + entry("http", r -> r.http(true)), + entry("indices", r -> r.indices(true)), + entry("process", r -> r.process(true)), + entry("breaker", r -> r.breaker(true)), + entry("script", r -> r.script(true)), + entry("discovery", r -> r.discovery(true)), + entry("ingest", r -> r.ingest(true)), + entry("adaptive_selection", r -> r.adaptiveSelection(true))); static final Map> FLAGS; diff --git a/server/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java b/server/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java index 58dc861126bfe..69a659faf4dc0 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java @@ -30,9 +30,6 @@ import org.elasticsearch.rest.RestStatus; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.Set; import static org.elasticsearch.rest.action.cat.RestTable.buildHelpWidths; @@ -76,8 +73,7 @@ public RestChannelConsumer prepareRequest(final RestRequest request, final NodeC } } - static Set RESPONSE_PARAMS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList("format", "h", "v", "ts", "pri", "bytes", "size", "time", "s"))); + static Set RESPONSE_PARAMS = Set.of("format", "h", "v", "ts", "pri", "bytes", "size", "time", "s"); @Override protected Set responseParams() { diff --git a/server/src/main/java/org/elasticsearch/script/AbstractSortScript.java b/server/src/main/java/org/elasticsearch/script/AbstractSortScript.java index 13b109766af83..ff2cafcc37f50 100644 --- a/server/src/main/java/org/elasticsearch/script/AbstractSortScript.java +++ b/server/src/main/java/org/elasticsearch/script/AbstractSortScript.java @@ -18,10 +18,6 @@ */ package org.elasticsearch.script; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.Scorable; import org.elasticsearch.ElasticsearchException; @@ -30,24 +26,17 @@ import org.elasticsearch.search.lookup.LeafSearchLookup; import org.elasticsearch.search.lookup.SearchLookup; -abstract class AbstractSortScript implements ScorerAware { +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; - private static final Map DEPRECATIONS; +abstract class AbstractSortScript implements ScorerAware { - static { - Map deprecations = new HashMap<>(); - deprecations.put( + private static final Map DEPRECATIONS = Map.of( "doc", - "Accessing variable [doc] via [params.doc] from within a sort-script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( + "Accessing variable [doc] via [params.doc] from within a sort-script is deprecated in favor of directly accessing [doc].", "_doc", - "Accessing variable [doc] via [params._doc] from within a sort-script " + - "is deprecated in favor of directly accessing [doc]." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + "Accessing variable [doc] via [params._doc] from within a sort-script is deprecated in favor of directly accessing [doc]."); /** * The generic runtime parameters for the script. diff --git a/server/src/main/java/org/elasticsearch/script/AggregationScript.java b/server/src/main/java/org/elasticsearch/script/AggregationScript.java index f48d097355110..d6ef2e7b14be2 100644 --- a/server/src/main/java/org/elasticsearch/script/AggregationScript.java +++ b/server/src/main/java/org/elasticsearch/script/AggregationScript.java @@ -18,10 +18,6 @@ */ package org.elasticsearch.script; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.Scorable; import org.elasticsearch.ElasticsearchException; @@ -30,28 +26,23 @@ import org.elasticsearch.search.lookup.LeafSearchLookup; import org.elasticsearch.search.lookup.SearchLookup; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + public abstract class AggregationScript implements ScorerAware { public static final String[] PARAMETERS = {}; public static final ScriptContext CONTEXT = new ScriptContext<>("aggs", Factory.class); - private static final Map DEPRECATIONS; - - static { - Map deprecations = new HashMap<>(); - deprecations.put( + private static final Map DEPRECATIONS = Map.of( "doc", - "Accessing variable [doc] via [params.doc] from within an aggregation-script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( + "Accessing variable [doc] via [params.doc] from within an aggregation-script " + + "is deprecated in favor of directly accessing [doc].", "_doc", - "Accessing variable [doc] via [params._doc] from within an aggregation-script " + - "is deprecated in favor of directly accessing [doc]." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + "Accessing variable [doc] via [params._doc] from within an aggregation-script " + + "is deprecated in favor of directly accessing [doc]."); /** * The generic runtime parameters for the script. diff --git a/server/src/main/java/org/elasticsearch/script/ClassPermission.java b/server/src/main/java/org/elasticsearch/script/ClassPermission.java index f636a0190c47f..dfef473398a86 100644 --- a/server/src/main/java/org/elasticsearch/script/ClassPermission.java +++ b/server/src/main/java/org/elasticsearch/script/ClassPermission.java @@ -23,7 +23,6 @@ import java.security.Permission; import java.security.PermissionCollection; import java.util.Arrays; -import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; @@ -75,30 +74,30 @@ */ public final class ClassPermission extends BasicPermission { public static final String STANDARD = "<>"; + // jdk classes /** Typical set of classes for scripting: basic data types, math, dates, and simple collections */ // this is the list from the old grovy sandbox impl (+ some things like String, Iterator, etc that were missing) - public static final Set STANDARD_CLASSES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - // jdk classes - java.lang.Boolean.class.getName(), - java.lang.Byte.class.getName(), - java.lang.Character.class.getName(), - java.lang.Double.class.getName(), - java.lang.Integer.class.getName(), - java.lang.Long.class.getName(), - java.lang.Math.class.getName(), - java.lang.Object.class.getName(), - java.lang.Short.class.getName(), - java.lang.String.class.getName(), + private static final Set STANDARD_CLASSES = Set.of( + Boolean.class.getName(), + Byte.class.getName(), + Character.class.getName(), + Double.class.getName(), + Integer.class.getName(), + Long.class.getName(), + Math.class.getName(), + Object.class.getName(), + Short.class.getName(), + String.class.getName(), java.math.BigDecimal.class.getName(), java.util.ArrayList.class.getName(), - java.util.Arrays.class.getName(), + Arrays.class.getName(), java.util.Date.class.getName(), java.util.HashMap.class.getName(), - java.util.HashSet.class.getName(), + HashSet.class.getName(), java.util.Iterator.class.getName(), java.util.List.class.getName(), java.util.Map.class.getName(), - java.util.Set.class.getName(), + Set.class.getName(), java.util.UUID.class.getName(), // joda-time org.joda.time.DateTime.class.getName(), @@ -106,8 +105,7 @@ public final class ClassPermission extends BasicPermission { org.joda.time.DateTimeZone.class.getName(), org.joda.time.Instant.class.getName(), org.joda.time.ReadableDateTime.class.getName(), - org.joda.time.ReadableInstant.class.getName() - ))); + org.joda.time.ReadableInstant.class.getName()); /** * Creates a new ClassPermission object. diff --git a/server/src/main/java/org/elasticsearch/script/FieldScript.java b/server/src/main/java/org/elasticsearch/script/FieldScript.java index 7707301ab4c1d..806c5b92cb9e3 100644 --- a/server/src/main/java/org/elasticsearch/script/FieldScript.java +++ b/server/src/main/java/org/elasticsearch/script/FieldScript.java @@ -25,7 +25,6 @@ import org.elasticsearch.search.lookup.SearchLookup; import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -36,22 +35,11 @@ public abstract class FieldScript { public static final String[] PARAMETERS = {}; - private static final Map DEPRECATIONS; - - static { - Map deprecations = new HashMap<>(); - deprecations.put( + private static final Map DEPRECATIONS = Map.of( "doc", - "Accessing variable [doc] via [params.doc] from within a field script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( + "Accessing variable [doc] via [params.doc] from within a field script is deprecated in favor of directly accessing [doc].", "_doc", - "Accessing variable [doc] via [params._doc] from within a field script " + - "is deprecated in favor of directly accessing [doc]." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + "Accessing variable [doc] via [params._doc] from within a field script is deprecated in favor of directly accessing [doc]."); /** The generic runtime parameters for the script. */ private final Map params; diff --git a/server/src/main/java/org/elasticsearch/script/ScoreScript.java b/server/src/main/java/org/elasticsearch/script/ScoreScript.java index f31af4c008c74..f681a2e5f6092 100644 --- a/server/src/main/java/org/elasticsearch/script/ScoreScript.java +++ b/server/src/main/java/org/elasticsearch/script/ScoreScript.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.io.UncheckedIOException; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.DoubleSupplier; @@ -36,21 +35,12 @@ */ public abstract class ScoreScript { - private static final Map DEPRECATIONS; - static { - Map deprecations = new HashMap<>(); - deprecations.put( + private static final Map DEPRECATIONS = Map.of( "doc", - "Accessing variable [doc] via [params.doc] from within a score script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( - "_doc", - "Accessing variable [doc] via [params._doc] from within a score script " + - "is deprecated in favor of directly accessing [doc]." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + "Accessing variable [doc] via [params.doc] from within a score script " + + "is deprecated in favor of directly accessing [doc].", + "_doc", "Accessing variable [doc] via [params._doc] from within a score script " + + "is deprecated in favor of directly accessing [doc]."); public static final String[] PARAMETERS = new String[]{}; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptedMetricAggContexts.java b/server/src/main/java/org/elasticsearch/script/ScriptedMetricAggContexts.java index f1c3e996ec8be..53c1aa3da1bd4 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptedMetricAggContexts.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptedMetricAggContexts.java @@ -27,7 +27,6 @@ import org.elasticsearch.search.lookup.SearchLookup; import java.io.IOException; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -62,27 +61,14 @@ public interface Factory { } public abstract static class MapScript { - private static final Map DEPRECATIONS; - - static { - Map deprecations = new HashMap<>(); - deprecations.put( + private static final Map DEPRECATIONS = Map.of( "doc", - "Accessing variable [doc] via [params.doc] from within a scripted metric agg map script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( - "_doc", - "Accessing variable [doc] via [params._doc] from within a scripted metric agg map script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( - "_agg", - "Accessing variable [_agg] via [params._agg] from within a scripted metric agg map script " + - "is deprecated in favor of using [state]." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + "Accessing variable [doc] via [params.doc] from within a scripted metric agg map script " + + "is deprecated in favor of directly accessing [doc].", + "_doc", "Accessing variable [doc] via [params._doc] from within a scripted metric agg map script " + + "is deprecated in favor of directly accessing [doc].", + "_agg", "Accessing variable [_agg] via [params._agg] from within a scripted metric agg map script " + + "is deprecated in favor of using [state]."); private final Map params; private final Map state; diff --git a/server/src/main/java/org/elasticsearch/script/TermsSetQueryScript.java b/server/src/main/java/org/elasticsearch/script/TermsSetQueryScript.java index c651c3ce69041..b3d29ff50f278 100644 --- a/server/src/main/java/org/elasticsearch/script/TermsSetQueryScript.java +++ b/server/src/main/java/org/elasticsearch/script/TermsSetQueryScript.java @@ -18,37 +18,28 @@ */ package org.elasticsearch.script; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; import org.apache.lucene.index.LeafReaderContext; import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.search.lookup.LeafSearchLookup; import org.elasticsearch.search.lookup.SearchLookup; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + public abstract class TermsSetQueryScript { public static final String[] PARAMETERS = {}; public static final ScriptContext CONTEXT = new ScriptContext<>("terms_set", Factory.class); - private static final Map DEPRECATIONS; - - static { - Map deprecations = new HashMap<>(); - deprecations.put( + private static final Map DEPRECATIONS = Map.of( "doc", - "Accessing variable [doc] via [params.doc] from within a terms-set-query-script " + - "is deprecated in favor of directly accessing [doc]." - ); - deprecations.put( + "Accessing variable [doc] via [params.doc] from within a terms-set-query-script " + + "is deprecated in favor of directly accessing [doc].", "_doc", - "Accessing variable [doc] via [params._doc] from within a terms-set-query-script " + - "is deprecated in favor of directly accessing [doc]." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + "Accessing variable [doc] via [params._doc] from within a terms-set-query-script " + + "is deprecated in favor of directly accessing [doc]."); /** * The generic runtime parameters for the script. diff --git a/server/src/main/java/org/elasticsearch/script/UpdateScript.java b/server/src/main/java/org/elasticsearch/script/UpdateScript.java index 765489b7e4449..ae0827ff83934 100644 --- a/server/src/main/java/org/elasticsearch/script/UpdateScript.java +++ b/server/src/main/java/org/elasticsearch/script/UpdateScript.java @@ -20,8 +20,6 @@ package org.elasticsearch.script; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; /** @@ -29,15 +27,8 @@ */ public abstract class UpdateScript { - private static final Map DEPRECATIONS; - static { - Map deprecations = new HashMap<>(); - deprecations.put( - "_type", - "[types removal] Looking up doc types [_type] in scripts is deprecated." - ); - DEPRECATIONS = Collections.unmodifiableMap(deprecations); - } + private static final Map DEPRECATIONS = + Map.of("_type", "[types removal] Looking up doc types [_type] in scripts is deprecated."); public static final String[] PARAMETERS = { }; diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/DateHistogramAggregationBuilder.java b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/DateHistogramAggregationBuilder.java index d607f4bfaf204..dc5af1582f15a 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/DateHistogramAggregationBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/DateHistogramAggregationBuilder.java @@ -59,12 +59,11 @@ import java.time.ZoneId; import java.time.ZoneOffset; import java.time.zone.ZoneOffsetTransition; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import static java.util.Collections.unmodifiableMap; +import static java.util.Map.entry; /** * A builder for histograms on date fields. @@ -75,28 +74,23 @@ public class DateHistogramAggregationBuilder extends ValuesSourceAggregationBuil public static final String NAME = "date_histogram"; private static DateMathParser EPOCH_MILLIS_PARSER = DateFormatter.forPattern("epoch_millis").toDateMathParser(); - public static final Map DATE_FIELD_UNITS; - - static { - Map dateFieldUnits = new HashMap<>(); - dateFieldUnits.put("year", Rounding.DateTimeUnit.YEAR_OF_CENTURY); - dateFieldUnits.put("1y", Rounding.DateTimeUnit.YEAR_OF_CENTURY); - dateFieldUnits.put("quarter", Rounding.DateTimeUnit.QUARTER_OF_YEAR); - dateFieldUnits.put("1q", Rounding.DateTimeUnit.QUARTER_OF_YEAR); - dateFieldUnits.put("month", Rounding.DateTimeUnit.MONTH_OF_YEAR); - dateFieldUnits.put("1M", Rounding.DateTimeUnit.MONTH_OF_YEAR); - dateFieldUnits.put("week", Rounding.DateTimeUnit.WEEK_OF_WEEKYEAR); - dateFieldUnits.put("1w", Rounding.DateTimeUnit.WEEK_OF_WEEKYEAR); - dateFieldUnits.put("day", Rounding.DateTimeUnit.DAY_OF_MONTH); - dateFieldUnits.put("1d", Rounding.DateTimeUnit.DAY_OF_MONTH); - dateFieldUnits.put("hour", Rounding.DateTimeUnit.HOUR_OF_DAY); - dateFieldUnits.put("1h", Rounding.DateTimeUnit.HOUR_OF_DAY); - dateFieldUnits.put("minute", Rounding.DateTimeUnit.MINUTES_OF_HOUR); - dateFieldUnits.put("1m", Rounding.DateTimeUnit.MINUTES_OF_HOUR); - dateFieldUnits.put("second", Rounding.DateTimeUnit.SECOND_OF_MINUTE); - dateFieldUnits.put("1s", Rounding.DateTimeUnit.SECOND_OF_MINUTE); - DATE_FIELD_UNITS = unmodifiableMap(dateFieldUnits); - } + public static final Map DATE_FIELD_UNITS = Map.ofEntries( + entry("year", Rounding.DateTimeUnit.YEAR_OF_CENTURY), + entry("1y", Rounding.DateTimeUnit.YEAR_OF_CENTURY), + entry("quarter", Rounding.DateTimeUnit.QUARTER_OF_YEAR), + entry("1q", Rounding.DateTimeUnit.QUARTER_OF_YEAR), + entry("month", Rounding.DateTimeUnit.MONTH_OF_YEAR), + entry("1M", Rounding.DateTimeUnit.MONTH_OF_YEAR), + entry("week", Rounding.DateTimeUnit.WEEK_OF_WEEKYEAR), + entry("1w", Rounding.DateTimeUnit.WEEK_OF_WEEKYEAR), + entry("day", Rounding.DateTimeUnit.DAY_OF_MONTH), + entry("1d", Rounding.DateTimeUnit.DAY_OF_MONTH), + entry("hour", Rounding.DateTimeUnit.HOUR_OF_DAY), + entry("1h", Rounding.DateTimeUnit.HOUR_OF_DAY), + entry("minute", Rounding.DateTimeUnit.MINUTES_OF_HOUR), + entry("1m", Rounding.DateTimeUnit.MINUTES_OF_HOUR), + entry("second", Rounding.DateTimeUnit.SECOND_OF_MINUTE), + entry("1s", Rounding.DateTimeUnit.SECOND_OF_MINUTE)); private static final ObjectParser PARSER; static { diff --git a/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java b/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java index e76206d6cba2a..14e5e660e1f67 100644 --- a/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java +++ b/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java @@ -21,35 +21,25 @@ import org.apache.lucene.index.LeafReaderContext; -import java.util.HashMap; import java.util.Map; -import static java.util.Collections.unmodifiableMap; - /** * Per-segment version of {@link SearchLookup}. */ public class LeafSearchLookup { - final LeafReaderContext ctx; - final LeafDocLookup docMap; - final SourceLookup sourceLookup; - final LeafFieldsLookup fieldsLookup; - final Map asMap; + private final LeafReaderContext ctx; + private final LeafDocLookup docMap; + private final SourceLookup sourceLookup; + private final LeafFieldsLookup fieldsLookup; + private final Map asMap; - public LeafSearchLookup(LeafReaderContext ctx, LeafDocLookup docMap, SourceLookup sourceLookup, - LeafFieldsLookup fieldsLookup) { + public LeafSearchLookup(LeafReaderContext ctx, LeafDocLookup docMap, SourceLookup sourceLookup, LeafFieldsLookup fieldsLookup) { this.ctx = ctx; this.docMap = docMap; this.sourceLookup = sourceLookup; this.fieldsLookup = fieldsLookup; - - Map asMap = new HashMap<>(4); - asMap.put("doc", docMap); - asMap.put("_doc", docMap); - asMap.put("_source", sourceLookup); - asMap.put("_fields", fieldsLookup); - this.asMap = unmodifiableMap(asMap); + this.asMap = Map.of("doc", docMap, "_doc", docMap, "_source", sourceLookup, "_fields", fieldsLookup); } public Map asMap() { diff --git a/server/src/main/java/org/elasticsearch/search/sort/SortBuilder.java b/server/src/main/java/org/elasticsearch/search/sort/SortBuilder.java index abef6d8ebec33..b4358abee0728 100644 --- a/server/src/main/java/org/elasticsearch/search/sort/SortBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/sort/SortBuilder.java @@ -40,13 +40,11 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder; public abstract class SortBuilder> implements NamedWriteable, ToXContentObject, Rewriteable> { @@ -58,16 +56,12 @@ public abstract class SortBuilder> implements NamedWrit public static final ParseField NESTED_FILTER_FIELD = new ParseField("nested_filter"); public static final ParseField NESTED_PATH_FIELD = new ParseField("nested_path"); - private static final Map> PARSERS; - static { - Map> parsers = new HashMap<>(); - parsers.put(ScriptSortBuilder.NAME, ScriptSortBuilder::fromXContent); - parsers.put(GeoDistanceSortBuilder.NAME, GeoDistanceSortBuilder::fromXContent); - parsers.put(GeoDistanceSortBuilder.ALTERNATIVE_NAME, GeoDistanceSortBuilder::fromXContent); - parsers.put(ScoreSortBuilder.NAME, ScoreSortBuilder::fromXContent); - // FieldSortBuilder gets involved if the user specifies a name that isn't one of these. - PARSERS = unmodifiableMap(parsers); - } + private static final Map> PARSERS = Map.of( + ScriptSortBuilder.NAME, ScriptSortBuilder::fromXContent, + GeoDistanceSortBuilder.NAME, GeoDistanceSortBuilder::fromXContent, + GeoDistanceSortBuilder.ALTERNATIVE_NAME, GeoDistanceSortBuilder::fromXContent, + // TODO: this can deadlock as it might access the ScoreSortBuilder (subclass) initializer from the SortBuilder initializer!!! + ScoreSortBuilder.NAME, ScoreSortBuilder::fromXContent); /** * Create a @link {@link SortFieldAndFormat} from this builder. diff --git a/server/src/main/java/org/elasticsearch/transport/RemoteClusterConnection.java b/server/src/main/java/org/elasticsearch/transport/RemoteClusterConnection.java index f4a1b250e7f5e..6b6ce18cfefbb 100644 --- a/server/src/main/java/org/elasticsearch/transport/RemoteClusterConnection.java +++ b/server/src/main/java/org/elasticsearch/transport/RemoteClusterConnection.java @@ -154,7 +154,7 @@ synchronized void updateSeedNodes( final String proxyAddress, final List>> seedNodes, final ActionListener connectListener) { - this.seedNodes = Collections.unmodifiableList(new ArrayList<>(seedNodes)); + this.seedNodes = List.copyOf(seedNodes); this.proxyAddress = proxyAddress; connectHandler.connect(connectListener); } diff --git a/server/src/main/java/org/elasticsearch/transport/TransportService.java b/server/src/main/java/org/elasticsearch/transport/TransportService.java index c8493edc97983..529aedae653da 100644 --- a/server/src/main/java/org/elasticsearch/transport/TransportService.java +++ b/server/src/main/java/org/elasticsearch/transport/TransportService.java @@ -56,9 +56,7 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.net.UnknownHostException; -import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -757,17 +755,15 @@ public TransportAddress[] addressesFromString(String address, int perAddressLimi /** * A set of all valid action prefixes. */ - public static final Set VALID_ACTION_PREFIXES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - "indices:admin", - "indices:monitor", - "indices:data/write", - "indices:data/read", - "indices:internal", - "cluster:admin", - "cluster:monitor", - "cluster:internal", - "internal:" - ))); + public static final Set VALID_ACTION_PREFIXES = Set.of( + "indices:admin", + "indices:monitor", "indices:data/write", + "indices:data/read", + "indices:internal", + "cluster:admin", + "cluster:monitor", + "cluster:internal", + "internal:"); private void validateActionName(String actionName) { // TODO we should makes this a hard validation and throw an exception but we need a good way to add backwards layer diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/RecordingTaskManagerListener.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/RecordingTaskManagerListener.java index 5046a48b938f6..5050dac2a4e3f 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/RecordingTaskManagerListener.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/RecordingTaskManagerListener.java @@ -64,7 +64,7 @@ public void waitForTaskCompletion(Task task) { } public synchronized List> getEvents() { - return Collections.unmodifiableList(new ArrayList<>(events)); + return List.copyOf(events); } public synchronized List getRegistrationEvents() { diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TestTaskPlugin.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TestTaskPlugin.java index 18e5702ed6a77..d39ab823dc490 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TestTaskPlugin.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TestTaskPlugin.java @@ -23,8 +23,8 @@ import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.FailedNodeException; +import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.TaskOperationFailure; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.nodes.BaseNodeRequest; @@ -49,8 +49,8 @@ import org.elasticsearch.common.xcontent.ToXContentFragment; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.plugins.ActionPlugin; -import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.NetworkPlugin; +import org.elasticsearch.plugins.Plugin; import org.elasticsearch.tasks.CancellableTask; import org.elasticsearch.tasks.Task; import org.elasticsearch.tasks.TaskId; @@ -59,10 +59,10 @@ import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportInterceptor; import org.elasticsearch.transport.TransportRequest; -import org.elasticsearch.transport.TransportService; import org.elasticsearch.transport.TransportRequestOptions; import org.elasticsearch.transport.TransportResponse; import org.elasticsearch.transport.TransportResponseHandler; +import org.elasticsearch.transport.TransportService; import java.io.IOException; import java.util.ArrayList; @@ -416,7 +416,7 @@ public static class UnblockTestTasksResponse extends BaseTasksResponse { public UnblockTestTasksResponse(List tasks, List taskFailures, List nodeFailures) { super(taskFailures, nodeFailures); - this.tasks = tasks == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(tasks)); + this.tasks = tasks == null ? Collections.emptyList() : List.copyOf(tasks); } public UnblockTestTasksResponse(StreamInput in) throws IOException { diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java index ec8af36dbf27e..e9b940df3847d 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java @@ -205,7 +205,7 @@ static class TestTasksResponse extends BaseTasksResponse { TestTasksResponse(List tasks, List taskFailures, List nodeFailures) { super(taskFailures, nodeFailures); - this.tasks = tasks == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(tasks)); + this.tasks = tasks == null ? Collections.emptyList() : List.copyOf(tasks); } TestTasksResponse(StreamInput in) throws IOException { diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java index 8d1a306f26094..dfef08944de60 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java @@ -44,13 +44,11 @@ import org.elasticsearch.test.rest.FakeRestRequest; import java.io.IOException; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; -import static java.util.Collections.unmodifiableList; import static org.elasticsearch.common.unit.TimeValue.timeValueMillis; /** @@ -58,18 +56,20 @@ */ public class ClusterRerouteRequestTests extends ESTestCase { private static final int ROUNDS = 30; - private final List> RANDOM_COMMAND_GENERATORS = unmodifiableList( - Arrays.> asList( - () -> new AllocateReplicaAllocationCommand(randomAlphaOfLengthBetween(2, 10), between(0, 1000), - randomAlphaOfLengthBetween(2, 10)), - () -> new AllocateEmptyPrimaryAllocationCommand(randomAlphaOfLengthBetween(2, 10), between(0, 1000), - randomAlphaOfLengthBetween(2, 10), randomBoolean()), - () -> new AllocateStalePrimaryAllocationCommand(randomAlphaOfLengthBetween(2, 10), between(0, 1000), - randomAlphaOfLengthBetween(2, 10), randomBoolean()), - () -> new CancelAllocationCommand(randomAlphaOfLengthBetween(2, 10), between(0, 1000), - randomAlphaOfLengthBetween(2, 10), randomBoolean()), - () -> new MoveAllocationCommand(randomAlphaOfLengthBetween(2, 10), between(0, 1000), - randomAlphaOfLengthBetween(2, 10), randomAlphaOfLengthBetween(2, 10)))); + private final List> RANDOM_COMMAND_GENERATORS = List.of( + () -> new AllocateReplicaAllocationCommand( + randomAlphaOfLengthBetween(2, 10), between(0, 1000), randomAlphaOfLengthBetween(2, 10)), + () -> new AllocateEmptyPrimaryAllocationCommand( + randomAlphaOfLengthBetween(2, 10), between(0, 1000), randomAlphaOfLengthBetween(2, 10), randomBoolean()), + () -> new AllocateStalePrimaryAllocationCommand( + randomAlphaOfLengthBetween(2, 10), between(0, 1000), randomAlphaOfLengthBetween(2, 10), randomBoolean()), + () -> new CancelAllocationCommand( + randomAlphaOfLengthBetween(2, 10), between(0, 1000), randomAlphaOfLengthBetween(2, 10), randomBoolean()), + () -> new MoveAllocationCommand( + randomAlphaOfLengthBetween(2, 10), + between(0, 1000), + randomAlphaOfLengthBetween(2, 10), + randomAlphaOfLengthBetween(2, 10))); private final NamedWriteableRegistry namedWriteableRegistry; public ClusterRerouteRequestTests() { diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java index 8f2db1281485d..ca0db0feb90f6 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java @@ -42,9 +42,7 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.gateway.TestGatewayAllocator; -import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import static java.util.Collections.emptyMap; import static org.hamcrest.Matchers.equalTo; @@ -217,6 +215,6 @@ public void testShrinkIndexSettings() { private DiscoveryNode newNode(String nodeId) { return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA))), Version.CURRENT); + java.util.Set.of(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA), Version.CURRENT); } } diff --git a/server/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java b/server/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java index a6e50170d7e80..df415d713d103 100644 --- a/server/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java +++ b/server/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java @@ -20,13 +20,10 @@ package org.elasticsearch.bootstrap; import org.elasticsearch.test.ESTestCase; -import org.junit.Before; import java.io.IOError; import java.io.IOException; import java.io.UncheckedIOException; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -36,19 +33,12 @@ public class ElasticsearchUncaughtExceptionHandlerTests extends ESTestCase { - private Map, Integer> expectedStatus; - - @Before - public void setUp() throws Exception { - super.setUp(); - Map, Integer> expectedStatus = new HashMap<>(); - expectedStatus.put(InternalError.class, 128); - expectedStatus.put(OutOfMemoryError.class, 127); - expectedStatus.put(StackOverflowError.class, 126); - expectedStatus.put(UnknownError.class, 125); - expectedStatus.put(IOError.class, 124); - this.expectedStatus = Collections.unmodifiableMap(expectedStatus); - } + private static Map, Integer> EXPECTED_STATUS = Map.of( + InternalError.class, 128, + OutOfMemoryError.class, 127, + StackOverflowError.class, 126, + UnknownError.class, 125, + IOError.class, 124); public void testUncaughtError() throws InterruptedException { final Error error = randomFrom( @@ -89,8 +79,8 @@ void onNonFatalUncaught(String threadName, Throwable t) { thread.join(); assertTrue(halt.get()); final int status; - if (expectedStatus.containsKey(error.getClass())) { - status = expectedStatus.get(error.getClass()); + if (EXPECTED_STATUS.containsKey(error.getClass())) { + status = EXPECTED_STATUS.get(error.getClass()); } else { status = 1; } diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java index ec89e085f0784..e3ba62b3b79ab 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java @@ -50,7 +50,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; @@ -409,8 +408,11 @@ private void runPrepareResizeIndexSettingsTest( } private DiscoveryNode newNode(String nodeId) { - return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA))), Version.CURRENT); + return new DiscoveryNode( + nodeId, + buildNewFakeTransportAddress(), + emptyMap(), + Set.of(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA), Version.CURRENT); } public void testValidateIndexName() throws Exception { diff --git a/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java b/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java index e9bae772f4ea0..9b9ae787545c1 100644 --- a/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java @@ -253,12 +253,9 @@ public void testAttributePreferenceRouting() { Map node1Attributes = new HashMap<>(); node1Attributes.put("rack_id", "rack_1"); node1Attributes.put("zone", "zone1"); - Map node2Attributes = new HashMap<>(); - node2Attributes.put("rack_id", "rack_2"); - node2Attributes.put("zone", "zone2"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() .add(newNode("node1", unmodifiableMap(node1Attributes))) - .add(newNode("node2", unmodifiableMap(node2Attributes))) + .add(newNode("node2", Map.of("rack_id", "rack_2", "zone", "zone2"))) .localNodeId("node1") ).build(); clusterState = strategy.reroute(clusterState, "reroute"); diff --git a/server/src/test/java/org/elasticsearch/index/mapper/ExternalMapperPlugin.java b/server/src/test/java/org/elasticsearch/index/mapper/ExternalMapperPlugin.java index 0824e1e0afcc7..6f1a96992f5d6 100644 --- a/server/src/test/java/org/elasticsearch/index/mapper/ExternalMapperPlugin.java +++ b/server/src/test/java/org/elasticsearch/index/mapper/ExternalMapperPlugin.java @@ -19,15 +19,12 @@ package org.elasticsearch.index.mapper; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.elasticsearch.index.mapper.Mapper; -import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.plugins.MapperPlugin; import org.elasticsearch.plugins.Plugin; +import java.util.Collections; +import java.util.Map; + public class ExternalMapperPlugin extends Plugin implements MapperPlugin { public static final String EXTERNAL = "external"; @@ -36,12 +33,11 @@ public class ExternalMapperPlugin extends Plugin implements MapperPlugin { @Override public Map getMappers() { - Map mappers = new HashMap<>(); - mappers.put(EXTERNAL, new ExternalMapper.TypeParser(EXTERNAL, "foo")); - mappers.put(EXTERNAL_BIS, new ExternalMapper.TypeParser(EXTERNAL_BIS, "bar")); - mappers.put(EXTERNAL_UPPER, new ExternalMapper.TypeParser(EXTERNAL_UPPER, "FOO BAR")); - mappers.put(FakeStringFieldMapper.CONTENT_TYPE, new FakeStringFieldMapper.TypeParser()); - return Collections.unmodifiableMap(mappers); + return Map.of( + EXTERNAL, new ExternalMapper.TypeParser(EXTERNAL, "foo"), + EXTERNAL_BIS, new ExternalMapper.TypeParser(EXTERNAL_BIS, "bar"), + EXTERNAL_UPPER, new ExternalMapper.TypeParser(EXTERNAL_UPPER, "FOO BAR"), + FakeStringFieldMapper.CONTENT_TYPE, new FakeStringFieldMapper.TypeParser()); } @Override diff --git a/server/src/test/java/org/elasticsearch/index/store/StoreTests.java b/server/src/test/java/org/elasticsearch/index/store/StoreTests.java index fc5870bc8e12c..9e8fae209dd81 100644 --- a/server/src/test/java/org/elasticsearch/index/store/StoreTests.java +++ b/server/src/test/java/org/elasticsearch/index/store/StoreTests.java @@ -825,10 +825,7 @@ protected Store.MetadataSnapshot createMetaDataSnapshot() { Map storeFileMetaDataMap = new HashMap<>(); storeFileMetaDataMap.put(storeFileMetaData1.name(), storeFileMetaData1); storeFileMetaDataMap.put(storeFileMetaData2.name(), storeFileMetaData2); - Map commitUserData = new HashMap<>(); - commitUserData.put("userdata_1", "test"); - commitUserData.put("userdata_2", "test"); - return new Store.MetadataSnapshot(unmodifiableMap(storeFileMetaDataMap), unmodifiableMap(commitUserData), 0); + return new Store.MetadataSnapshot(unmodifiableMap(storeFileMetaDataMap), Map.of("userdata_1", "test", "userdata_2", "test"), 0); } public void testUserDataRead() throws IOException { diff --git a/server/src/test/java/org/elasticsearch/persistent/PersistentTasksClusterServiceTests.java b/server/src/test/java/org/elasticsearch/persistent/PersistentTasksClusterServiceTests.java index c3863e8ec08e4..f29953633a1bb 100644 --- a/server/src/test/java/org/elasticsearch/persistent/PersistentTasksClusterServiceTests.java +++ b/server/src/test/java/org/elasticsearch/persistent/PersistentTasksClusterServiceTests.java @@ -51,10 +51,8 @@ import org.junit.BeforeClass; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; @@ -791,8 +789,11 @@ private String addTask(PersistentTasksCustomMetaData.Builder tasks, String param } private DiscoveryNode newNode(String nodeId) { - return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA))), + return new DiscoveryNode( + nodeId, + buildNewFakeTransportAddress(), + emptyMap(), + Set.of(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA), Version.CURRENT); } diff --git a/server/src/test/java/org/elasticsearch/persistent/TestPersistentTasksPlugin.java b/server/src/test/java/org/elasticsearch/persistent/TestPersistentTasksPlugin.java index 151129c0cc1fa..0b5c432d5978c 100644 --- a/server/src/test/java/org/elasticsearch/persistent/TestPersistentTasksPlugin.java +++ b/server/src/test/java/org/elasticsearch/persistent/TestPersistentTasksPlugin.java @@ -62,7 +62,6 @@ import org.elasticsearch.transport.TransportService; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -500,7 +499,7 @@ public static class TestTasksResponse extends BaseTasksResponse { public TestTasksResponse(List tasks, List taskFailures, List nodeFailures) { super(taskFailures, nodeFailures); - this.tasks = tasks == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(tasks)); + this.tasks = tasks == null ? Collections.emptyList() : List.copyOf(tasks); } public TestTasksResponse(StreamInput in) throws IOException { diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java b/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java index 012171ec25a0b..673b6b8e9dc91 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java @@ -3,7 +3,8 @@ * 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 + * 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 * @@ -11,8 +12,10 @@ * * 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 + * "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. */ @@ -54,30 +57,30 @@ import org.elasticsearch.search.aggregations.bucket.terms.DoubleTermsTests; import org.elasticsearch.search.aggregations.bucket.terms.LongTermsTests; import org.elasticsearch.search.aggregations.bucket.terms.StringTermsTests; +import org.elasticsearch.search.aggregations.metrics.InternalAvgTests; +import org.elasticsearch.search.aggregations.metrics.InternalCardinalityTests; import org.elasticsearch.search.aggregations.metrics.InternalExtendedStatsTests; +import org.elasticsearch.search.aggregations.metrics.InternalGeoBoundsTests; +import org.elasticsearch.search.aggregations.metrics.InternalGeoCentroidTests; +import org.elasticsearch.search.aggregations.metrics.InternalHDRPercentilesRanksTests; +import org.elasticsearch.search.aggregations.metrics.InternalHDRPercentilesTests; import org.elasticsearch.search.aggregations.metrics.InternalMaxTests; import org.elasticsearch.search.aggregations.metrics.InternalMedianAbsoluteDeviationTests; import org.elasticsearch.search.aggregations.metrics.InternalMinTests; +import org.elasticsearch.search.aggregations.metrics.InternalScriptedMetricTests; import org.elasticsearch.search.aggregations.metrics.InternalStatsBucketTests; import org.elasticsearch.search.aggregations.metrics.InternalStatsTests; import org.elasticsearch.search.aggregations.metrics.InternalSumTests; -import org.elasticsearch.search.aggregations.metrics.InternalAvgTests; -import org.elasticsearch.search.aggregations.metrics.InternalCardinalityTests; -import org.elasticsearch.search.aggregations.metrics.InternalGeoBoundsTests; -import org.elasticsearch.search.aggregations.metrics.InternalGeoCentroidTests; -import org.elasticsearch.search.aggregations.metrics.InternalHDRPercentilesRanksTests; -import org.elasticsearch.search.aggregations.metrics.InternalHDRPercentilesTests; import org.elasticsearch.search.aggregations.metrics.InternalTDigestPercentilesRanksTests; import org.elasticsearch.search.aggregations.metrics.InternalTDigestPercentilesTests; -import org.elasticsearch.search.aggregations.metrics.InternalScriptedMetricTests; import org.elasticsearch.search.aggregations.metrics.InternalTopHitsTests; import org.elasticsearch.search.aggregations.metrics.InternalValueCountTests; import org.elasticsearch.search.aggregations.metrics.InternalWeightedAvgTests; -import org.elasticsearch.search.aggregations.pipeline.InternalSimpleValueTests; import org.elasticsearch.search.aggregations.pipeline.InternalBucketMetricValueTests; -import org.elasticsearch.search.aggregations.pipeline.InternalPercentilesBucketTests; -import org.elasticsearch.search.aggregations.pipeline.InternalExtendedStatsBucketTests; import org.elasticsearch.search.aggregations.pipeline.InternalDerivativeTests; +import org.elasticsearch.search.aggregations.pipeline.InternalExtendedStatsBucketTests; +import org.elasticsearch.search.aggregations.pipeline.InternalPercentilesBucketTests; +import org.elasticsearch.search.aggregations.pipeline.InternalSimpleValueTests; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.InternalAggregationTestCase; import org.elasticsearch.test.InternalMultiBucketAggregationTestCase; @@ -87,7 +90,6 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Predicate; @@ -103,60 +105,55 @@ */ public class AggregationsTests extends ESTestCase { - private static final List> aggsTests = getAggsTests(); - - private static List> getAggsTests() { - List> aggsTests = new ArrayList<>(); - aggsTests.add(new InternalCardinalityTests()); - aggsTests.add(new InternalTDigestPercentilesTests()); - aggsTests.add(new InternalTDigestPercentilesRanksTests()); - aggsTests.add(new InternalHDRPercentilesTests()); - aggsTests.add(new InternalHDRPercentilesRanksTests()); - aggsTests.add(new InternalPercentilesBucketTests()); - aggsTests.add(new InternalMinTests()); - aggsTests.add(new InternalMaxTests()); - aggsTests.add(new InternalAvgTests()); - aggsTests.add(new InternalWeightedAvgTests()); - aggsTests.add(new InternalSumTests()); - aggsTests.add(new InternalValueCountTests()); - aggsTests.add(new InternalSimpleValueTests()); - aggsTests.add(new InternalDerivativeTests()); - aggsTests.add(new InternalBucketMetricValueTests()); - aggsTests.add(new InternalStatsTests()); - aggsTests.add(new InternalStatsBucketTests()); - aggsTests.add(new InternalExtendedStatsTests()); - aggsTests.add(new InternalExtendedStatsBucketTests()); - aggsTests.add(new InternalGeoBoundsTests()); - aggsTests.add(new InternalGeoCentroidTests()); - aggsTests.add(new InternalHistogramTests()); - aggsTests.add(new InternalDateHistogramTests()); - aggsTests.add(new InternalAutoDateHistogramTests()); - aggsTests.add(new LongTermsTests()); - aggsTests.add(new DoubleTermsTests()); - aggsTests.add(new StringTermsTests()); - aggsTests.add(new InternalMissingTests()); - aggsTests.add(new InternalNestedTests()); - aggsTests.add(new InternalReverseNestedTests()); - aggsTests.add(new InternalGlobalTests()); - aggsTests.add(new InternalFilterTests()); - aggsTests.add(new InternalSamplerTests()); - aggsTests.add(new GeoHashGridTests()); - aggsTests.add(new GeoTileGridTests()); - aggsTests.add(new InternalRangeTests()); - aggsTests.add(new InternalDateRangeTests()); - aggsTests.add(new InternalGeoDistanceTests()); - aggsTests.add(new InternalFiltersTests()); - aggsTests.add(new InternalAdjacencyMatrixTests()); - aggsTests.add(new SignificantLongTermsTests()); - aggsTests.add(new SignificantStringTermsTests()); - aggsTests.add(new InternalScriptedMetricTests()); - aggsTests.add(new InternalBinaryRangeTests()); - aggsTests.add(new InternalTopHitsTests()); - aggsTests.add(new InternalCompositeTests()); - aggsTests.add(new InternalMedianAbsoluteDeviationTests()); - return Collections.unmodifiableList(aggsTests); - } - + private static final List> aggsTests = List.of( + new InternalCardinalityTests(), + new InternalTDigestPercentilesTests(), + new InternalTDigestPercentilesRanksTests(), + new InternalHDRPercentilesTests(), + new InternalHDRPercentilesRanksTests(), + new InternalPercentilesBucketTests(), + new InternalMinTests(), + new InternalMaxTests(), + new InternalAvgTests(), + new InternalWeightedAvgTests(), + new InternalSumTests(), + new InternalValueCountTests(), + new InternalSimpleValueTests(), + new InternalDerivativeTests(), + new InternalBucketMetricValueTests(), + new InternalStatsTests(), + new InternalStatsBucketTests(), + new InternalExtendedStatsTests(), + new InternalExtendedStatsBucketTests(), + new InternalGeoBoundsTests(), + new InternalGeoCentroidTests(), + new InternalHistogramTests(), + new InternalDateHistogramTests(), + new InternalAutoDateHistogramTests(), + new LongTermsTests(), + new DoubleTermsTests(), + new StringTermsTests(), + new InternalMissingTests(), + new InternalNestedTests(), + new InternalReverseNestedTests(), + new InternalGlobalTests(), + new InternalFilterTests(), + new InternalSamplerTests(), + new GeoHashGridTests(), + new GeoTileGridTests(), + new InternalRangeTests(), + new InternalDateRangeTests(), + new InternalGeoDistanceTests(), + new InternalFiltersTests(), + new InternalAdjacencyMatrixTests(), + new SignificantLongTermsTests(), + new SignificantStringTermsTests(), + new InternalScriptedMetricTests(), + new InternalBinaryRangeTests(), + new InternalTopHitsTests(), + new InternalCompositeTests(), + new InternalMedianAbsoluteDeviationTests()); + @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(InternalAggregationTestCase.getDefaultNamedXContents()); @@ -182,7 +179,8 @@ public void cleanUp() throws Exception { } public void testAllAggsAreBeingTested() { - assertEquals(InternalAggregationTestCase.getDefaultNamedXContents().size(), aggsTests.size()); + assertEquals(InternalAggregationTestCase.getDefaultNamedXContents().size(), +aggsTests.size()); Set aggs = aggsTests.stream().map((testCase) -> testCase.createTestInstance().getType()).collect(Collectors.toSet()); for (NamedXContentRegistry.Entry entry : InternalAggregationTestCase.getDefaultNamedXContents()) { assertTrue(aggs.contains(entry.name.getPreferredName())); @@ -200,36 +198,47 @@ public void testFromXContentWithRandomFields() throws IOException { /** * Test that parsing works for a randomly created Aggregations object with a * randomized aggregation tree. The test randomly chooses an - * {@link XContentType}, randomizes the order of the {@link XContent} fields + * {@link XContentType}, +randomizes the order of the {@link XContent} fields * and randomly sets the `humanReadable` flag when rendering the * {@link XContent}. * * @param addRandomFields - * if set, this will also add random {@link XContent} fields to + * if set, +this will also add random {@link XContent} fields to * tests that the parsers are lenient to future additions to rest * responses */ private void parseAndAssert(boolean addRandomFields) throws IOException { XContentType xContentType = randomFrom(XContentType.values()); - final ToXContent.Params params = new ToXContent.MapParams(singletonMap(RestSearchAction.TYPED_KEYS_PARAM, "true")); + final ToXContent.Params params = new ToXContent.MapParams(singletonMap(RestSearchAction.TYPED_KEYS_PARAM, +"true")); Aggregations aggregations = createTestInstance(); - BytesReference originalBytes = toShuffledXContent(aggregations, xContentType, params, randomBoolean()); + BytesReference originalBytes = toShuffledXContent(aggregations, +xContentType, +params, +randomBoolean()); BytesReference mutated; if (addRandomFields) { /* * - don't insert into the root object because it should only contain the named aggregations to test * - * - don't insert into the "meta" object, because we pass on everything we find there + * - don't insert into the "meta" object, +because we pass on everything we find there * - * - we don't want to directly insert anything random into "buckets" objects, they are used with + * - we don't want to directly insert anything random into "buckets" objects, +they are used with * "keyed" aggregations and contain named bucket objects. Any new named object on this level should * also be a bucket and be parsed as such. * - * - we cannot insert randomly into VALUE or VALUES objects e.g. in Percentiles, the keys need to be numeric there + * - we cannot insert randomly into VALUE or VALUES objects e.g. in Percentiles, +the keys need to be numeric there * - * - we cannot insert into ExtendedMatrixStats "covariance" or "correlation" fields, their syntax is strict + * - we cannot insert into ExtendedMatrixStats "covariance" or "correlation" fields, +their syntax is strict * - * - exclude "key", it can be an array of objects and we need strict values + * - exclude "key", +it can be an array of objects and we need strict values */ Predicate excludes = path -> (path.isEmpty() || path.endsWith("aggregations") || path.endsWith(Aggregation.CommonFields.META.getPreferredName()) @@ -237,18 +246,30 @@ private void parseAndAssert(boolean addRandomFields) throws IOException { || path.endsWith(CommonFields.VALUES.getPreferredName()) || path.endsWith("covariance") || path.endsWith("correlation") || path.contains(CommonFields.VALUE.getPreferredName()) || path.endsWith(CommonFields.KEY.getPreferredName())); - mutated = insertRandomFields(xContentType, originalBytes, excludes, random()); + mutated = insertRandomFields(xContentType, +originalBytes, +excludes, +random()); } else { mutated = originalBytes; } - try (XContentParser parser = createParser(xContentType.xContent(), mutated)) { - assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); - assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); - assertEquals(Aggregations.AGGREGATIONS_FIELD, parser.currentName()); - assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); + try (XContentParser parser = createParser(xContentType.xContent(), +mutated)) { + assertEquals(XContentParser.Token.START_OBJECT, +parser.nextToken()); + assertEquals(XContentParser.Token.FIELD_NAME, +parser.nextToken()); + assertEquals(Aggregations.AGGREGATIONS_FIELD, +parser.currentName()); + assertEquals(XContentParser.Token.START_OBJECT, +parser.nextToken()); Aggregations parsedAggregations = Aggregations.fromXContent(parser); - BytesReference parsedBytes = XContentHelper.toXContent(parsedAggregations, xContentType, randomBoolean()); - ElasticsearchAssertions.assertToXContentEquivalent(originalBytes, parsedBytes, xContentType); + BytesReference parsedBytes = XContentHelper.toXContent(parsedAggregations, +xContentType, +randomBoolean()); + ElasticsearchAssertions.assertToXContentEquivalent(originalBytes, +parsedBytes, +xContentType); } } @@ -261,19 +282,28 @@ public void testParsingExceptionOnUnknownAggregation() throws IOException { } builder.endObject(); BytesReference originalBytes = BytesReference.bytes(builder); - try (XContentParser parser = createParser(builder.contentType().xContent(), originalBytes)) { - assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); - ParsingException ex = expectThrows(ParsingException.class, () -> Aggregations.fromXContent(parser)); - assertEquals("Could not parse aggregation keyed as [unknownAggregation]", ex.getMessage()); + try (XContentParser parser = createParser(builder.contentType().xContent(), +originalBytes)) { + assertEquals(XContentParser.Token.START_OBJECT, +parser.nextToken()); + ParsingException ex = expectThrows(ParsingException.class, +() -> Aggregations.fromXContent(parser)); + assertEquals("Could not parse aggregation keyed as [unknownAggregation]", +ex.getMessage()); } } public final InternalAggregations createTestInstance() { - return createTestInstance(1, 0, 5); + return createTestInstance(1, +0, +5); } - private static InternalAggregations createTestInstance(final int minNumAggs, final int currentDepth, final int maxDepth) { - int numAggs = randomIntBetween(minNumAggs, 4); + private static InternalAggregations createTestInstance(final int minNumAggs, +final int currentDepth, +final int maxDepth) { + int numAggs = randomIntBetween(minNumAggs, +4); List aggs = new ArrayList<>(numAggs); for (int i = 0; i < numAggs; i++) { InternalAggregationTestCase testCase = randomFrom(aggsTests); @@ -281,7 +311,9 @@ private static InternalAggregations createTestInstance(final int minNumAggs, fin InternalMultiBucketAggregationTestCase multiBucketAggTestCase = (InternalMultiBucketAggregationTestCase) testCase; if (currentDepth < maxDepth) { multiBucketAggTestCase.setSubAggregationsSupplier( - () -> createTestInstance(0, currentDepth + 1, maxDepth) + () -> createTestInstance(0, +currentDepth + 1, +maxDepth) ); } else { multiBucketAggTestCase.setSubAggregationsSupplier( @@ -291,7 +323,9 @@ private static InternalAggregations createTestInstance(final int minNumAggs, fin } else if (testCase instanceof InternalSingleBucketAggregationTestCase) { InternalSingleBucketAggregationTestCase singleBucketAggTestCase = (InternalSingleBucketAggregationTestCase) testCase; if (currentDepth < maxDepth) { - singleBucketAggTestCase.subAggregationsSupplier = () -> createTestInstance(0, currentDepth + 1, maxDepth); + singleBucketAggTestCase.subAggregationsSupplier = () -> createTestInstance(0, +currentDepth + 1, +maxDepth); } else { singleBucketAggTestCase.subAggregationsSupplier = () -> InternalAggregations.EMPTY; } diff --git a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index e41898727d7e2..cbafeb92f6765 100644 --- a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -2704,18 +2704,16 @@ public ClusterState execute(ClusterState currentState) { shards.put(new ShardId(idxName, "_na_", 0), new ShardSnapshotStatus("unknown-node", State.ABORTED, "aborted")); shards.put(new ShardId(idxName, "_na_", 1), new ShardSnapshotStatus("unknown-node", State.ABORTED, "aborted")); shards.put(new ShardId(idxName, "_na_", 2), new ShardSnapshotStatus("unknown-node", State.ABORTED, "aborted")); - List entries = new ArrayList<>(); - entries.add(new Entry(new Snapshot(repositoryName, - createSnapshotResponse.getSnapshotInfo().snapshotId()), - true, - false, - State.ABORTED, - Collections.singletonList(indexId), - System.currentTimeMillis(), - repositoryData.getGenId(), - shards.build())); return ClusterState.builder(currentState) - .putCustom(SnapshotsInProgress.TYPE, new SnapshotsInProgress(Collections.unmodifiableList(entries))) + .putCustom(SnapshotsInProgress.TYPE, new SnapshotsInProgress(List.of(new Entry(new Snapshot(repositoryName, + createSnapshotResponse.getSnapshotInfo().snapshotId()), + true, + false, + State.ABORTED, + Collections.singletonList(indexId), + System.currentTimeMillis(), + repositoryData.getGenId(), + shards.build())))) .build(); } diff --git a/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java index d657952260e81..134a91ac296c1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java @@ -1175,12 +1175,10 @@ private boolean isTransportClient(final Client client) { } private static final Set SAFE_METADATA_CUSTOMS = - Collections.unmodifiableSet( - new HashSet<>(Arrays.asList(IndexGraveyard.TYPE, IngestMetadata.TYPE, RepositoriesMetaData.TYPE, ScriptMetaData.TYPE))); + Set.of(IndexGraveyard.TYPE, IngestMetadata.TYPE, RepositoriesMetaData.TYPE, ScriptMetaData.TYPE); private static final Set SAFE_CUSTOMS = - Collections.unmodifiableSet( - new HashSet<>(Arrays.asList(RestoreInProgress.TYPE, SnapshotDeletionsInProgress.TYPE, SnapshotsInProgress.TYPE))); + Set.of(RestoreInProgress.TYPE, SnapshotDeletionsInProgress.TYPE, SnapshotsInProgress.TYPE); /** * Remove any customs except for customs that we know all clients understand. diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/Features.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/Features.java index bdcf426d118f3..c53627b0b15aa 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/Features.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/Features.java @@ -19,12 +19,9 @@ package org.elasticsearch.test.rest.yaml; -import java.util.Arrays; -import java.util.List; - import org.elasticsearch.test.rest.ESRestTestCase; -import static java.util.Collections.unmodifiableList; +import java.util.List; /** * Allows to register additional features supported by the tests runner. @@ -35,7 +32,8 @@ * and the related skip sections can be removed from the tests as well. */ public final class Features { - private static final List SUPPORTED = unmodifiableList(Arrays.asList( + + private static final List SUPPORTED = List.of( "catch_unauthorized", "default_shards", "embedded_stash_key", @@ -48,8 +46,7 @@ public final class Features { "yaml", "contains", "transform_and_set", - "arbitrary_key" - )); + "arbitrary_key"); private Features() { diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ExecutableSection.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ExecutableSection.java index 135a60cca3431..19690b235281f 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ExecutableSection.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ExecutableSection.java @@ -25,11 +25,8 @@ import org.elasticsearch.test.rest.yaml.ClientYamlTestExecutionContext; import java.io.IOException; -import java.util.Arrays; import java.util.List; -import static java.util.Collections.unmodifiableList; - /** * Represents a test fragment that can be executed (e.g. api call, assertion) */ @@ -37,7 +34,7 @@ public interface ExecutableSection { /** * Default list of {@link ExecutableSection}s available for tests. */ - List DEFAULT_EXECUTABLE_CONTEXTS = unmodifiableList(Arrays.asList( + List DEFAULT_EXECUTABLE_CONTEXTS = List.of( new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("do"), DoSection::parse), new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("set"), SetSection::parse), new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("transform_and_set"), TransformAndSetSection::parse), @@ -49,7 +46,7 @@ public interface ExecutableSection { new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("lt"), LessThanAssertion::parse), new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("lte"), LessThanOrEqualToAssertion::parse), new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("contains"), ContainsAssertion::parse), - new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("length"), LengthAssertion::parse))); + new NamedXContentRegistry.Entry(ExecutableSection.class, new ParseField("length"), LengthAssertion::parse)); /** * {@link NamedXContentRegistry} that parses the default list of diff --git a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java index 0ee86a6058c63..d80959b01ef3c 100644 --- a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java +++ b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java @@ -39,7 +39,9 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -191,6 +193,9 @@ synchronized void coordinateReads() { numOutstandingReads++; sendShardChangesRequest(from, requestOpCount, maxRequiredSeqNo); lastRequestedSeqNo = maxRequiredSeqNo; + Map s = new HashMap<>(); + s.put("a","b"); + Collections.unmodifiableMap(s); } if (numOutstandingReads == 0 && hasReadBudget()) { diff --git a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowTask.java b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowTask.java index 8852e81607c16..b00bf15782fa3 100644 --- a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowTask.java +++ b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowTask.java @@ -21,9 +21,7 @@ import org.elasticsearch.xpack.core.ccr.action.ImmutableFollowParameters; import java.io.IOException; -import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -34,7 +32,7 @@ public class ShardFollowTask extends ImmutableFollowParameters implements XPackP // list of headers that will be stored when a job is created public static final Set HEADER_FILTERS = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList("es-security-runas-user", "_xpack_security_authentication"))); + Set.of("es-security-runas-user", "_xpack_security_authentication"); private static final ParseField REMOTE_CLUSTER_FIELD = new ParseField("remote_cluster"); private static final ParseField FOLLOW_SHARD_INDEX_FIELD = new ParseField("follow_shard_index"); diff --git a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/TransportResumeFollowAction.java b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/TransportResumeFollowAction.java index cf35387c6ece4..ec71c93a33f30 100644 --- a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/TransportResumeFollowAction.java +++ b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/TransportResumeFollowAction.java @@ -50,8 +50,6 @@ import org.elasticsearch.xpack.core.ccr.action.ResumeFollowAction; import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Objects; @@ -351,98 +349,86 @@ static String[] extractLeaderShardHistoryUUIDs(Map ccrIndexMetaD * These dynamic settings don't affect how documents are indexed (affect index time text analysis) and / or * are inconvenient if they were replicated (e.g. changing number of replicas). */ - static final Set> NON_REPLICATED_SETTINGS; - - static { - final Set> nonReplicatedSettings = new HashSet<>(); - nonReplicatedSettings.add(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_AUTO_EXPAND_REPLICAS_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_ROUTING_EXCLUDE_GROUP_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_ROUTING_INCLUDE_GROUP_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_ROUTING_REQUIRE_GROUP_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_READ_ONLY_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_BLOCKS_READ_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_BLOCKS_WRITE_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_BLOCKS_METADATA_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_BLOCKS_READ_ONLY_ALLOW_DELETE_SETTING); - nonReplicatedSettings.add(IndexMetaData.INDEX_PRIORITY_SETTING); - nonReplicatedSettings.add(IndexMetaData.SETTING_WAIT_FOR_ACTIVE_SHARDS); - - nonReplicatedSettings.add(EnableAllocationDecider.INDEX_ROUTING_REBALANCE_ENABLE_SETTING); - nonReplicatedSettings.add(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING); - nonReplicatedSettings.add(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING); - nonReplicatedSettings.add(MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY); - nonReplicatedSettings.add(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING); - - nonReplicatedSettings.add(IndexSettings.MAX_RESULT_WINDOW_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_WARMER_ENABLED_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_REFRESH_INTERVAL_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_RESCORE_WINDOW_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING); - nonReplicatedSettings.add(IndexSettings.DEFAULT_FIELD_SETTING); - nonReplicatedSettings.add(IndexSettings.QUERY_STRING_LENIENT_SETTING); - nonReplicatedSettings.add(IndexSettings.QUERY_STRING_ANALYZE_WILDCARD); - nonReplicatedSettings.add(IndexSettings.QUERY_STRING_ALLOW_LEADING_WILDCARD); - nonReplicatedSettings.add(IndexSettings.ALLOW_UNMAPPED); - nonReplicatedSettings.add(IndexSettings.INDEX_SEARCH_IDLE_AFTER); - nonReplicatedSettings.add(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_SCRIPT_FIELDS_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_REGEX_LENGTH_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_TERMS_COUNT_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_ANALYZED_OFFSET_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_DOCVALUE_FIELDS_SEARCH_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_TOKEN_COUNT_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_SLICES_PER_SCROLL); - nonReplicatedSettings.add(IndexSettings.MAX_ADJACENCY_MATRIX_FILTERS_SETTING); - nonReplicatedSettings.add(IndexSettings.DEFAULT_PIPELINE); - nonReplicatedSettings.add(IndexSettings.INDEX_SEARCH_THROTTLED); - nonReplicatedSettings.add(IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING); - nonReplicatedSettings.add(IndexSettings.INDEX_GC_DELETES_SETTING); - nonReplicatedSettings.add(IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD); - - nonReplicatedSettings.add(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING); - nonReplicatedSettings.add(BitsetFilterCache.INDEX_LOAD_RANDOM_ACCESS_FILTERS_EAGERLY_SETTING); - - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING); - nonReplicatedSettings.add(SearchSlowLog.INDEX_SEARCH_SLOWLOG_LEVEL); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING); - nonReplicatedSettings.add(IndexingSlowLog.INDEX_INDEXING_SLOWLOG_MAX_SOURCE_CHARS_TO_LOG_SETTING); - - nonReplicatedSettings.add(MergePolicyConfig.INDEX_COMPOUND_FORMAT_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING); - nonReplicatedSettings.add(MergePolicyConfig.INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT_SETTING); - - nonReplicatedSettings.add(MergeSchedulerConfig.AUTO_THROTTLE_SETTING); - nonReplicatedSettings.add(MergeSchedulerConfig.MAX_MERGE_COUNT_SETTING); - nonReplicatedSettings.add(MergeSchedulerConfig.MAX_THREAD_COUNT_SETTING); - nonReplicatedSettings.add(EngineConfig.INDEX_CODEC_SETTING); - - NON_REPLICATED_SETTINGS = Collections.unmodifiableSet(nonReplicatedSettings); - } + static final Set> NON_REPLICATED_SETTINGS = Set.of( + IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING, + IndexMetaData.INDEX_AUTO_EXPAND_REPLICAS_SETTING, + IndexMetaData.INDEX_ROUTING_EXCLUDE_GROUP_SETTING, + IndexMetaData.INDEX_ROUTING_INCLUDE_GROUP_SETTING, + IndexMetaData.INDEX_ROUTING_REQUIRE_GROUP_SETTING, + IndexMetaData.INDEX_READ_ONLY_SETTING, + IndexMetaData.INDEX_BLOCKS_READ_SETTING, + IndexMetaData.INDEX_BLOCKS_WRITE_SETTING, + IndexMetaData.INDEX_BLOCKS_METADATA_SETTING, + IndexMetaData.INDEX_BLOCKS_READ_ONLY_ALLOW_DELETE_SETTING, + IndexMetaData.INDEX_PRIORITY_SETTING, + IndexMetaData.SETTING_WAIT_FOR_ACTIVE_SHARDS, + EnableAllocationDecider.INDEX_ROUTING_REBALANCE_ENABLE_SETTING, + EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING, + ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING, + MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY, + UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING, + IndexSettings.MAX_RESULT_WINDOW_SETTING, + IndexSettings.INDEX_WARMER_ENABLED_SETTING, + IndexSettings.INDEX_REFRESH_INTERVAL_SETTING, + IndexSettings.MAX_RESCORE_WINDOW_SETTING, + IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING, + IndexSettings.DEFAULT_FIELD_SETTING, + IndexSettings.QUERY_STRING_LENIENT_SETTING, + IndexSettings.QUERY_STRING_ANALYZE_WILDCARD, + IndexSettings.QUERY_STRING_ALLOW_LEADING_WILDCARD, + IndexSettings.ALLOW_UNMAPPED, + IndexSettings.INDEX_SEARCH_IDLE_AFTER, + IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING, + IndexSettings.INDEX_SOFT_DELETES_RETENTION_LEASE_PERIOD_SETTING, + IndexSettings.MAX_SCRIPT_FIELDS_SETTING, + IndexSettings.MAX_REGEX_LENGTH_SETTING, + IndexSettings.MAX_TERMS_COUNT_SETTING, + IndexSettings.MAX_ANALYZED_OFFSET_SETTING, + IndexSettings.MAX_DOCVALUE_FIELDS_SEARCH_SETTING, + IndexSettings.MAX_TOKEN_COUNT_SETTING, + IndexSettings.MAX_SLICES_PER_SCROLL, + IndexSettings.MAX_ADJACENCY_MATRIX_FILTERS_SETTING, + IndexSettings.DEFAULT_PIPELINE, + IndexSettings.INDEX_SEARCH_THROTTLED, + IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING, + IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING, + IndexSettings.INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING, + IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING, + IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING, + IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING, + IndexSettings.INDEX_GC_DELETES_SETTING, + IndexSettings.MAX_REFRESH_LISTENERS_PER_SHARD, + IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING, + BitsetFilterCache.INDEX_LOAD_RANDOM_ACCESS_FILTERS_EAGERLY_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING, + SearchSlowLog.INDEX_SEARCH_SLOWLOG_LEVEL, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_LEVEL_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_REFORMAT_SETTING, + IndexingSlowLog.INDEX_INDEXING_SLOWLOG_MAX_SOURCE_CHARS_TO_LOG_SETTING, + MergePolicyConfig.INDEX_COMPOUND_FORMAT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING, + MergePolicyConfig.INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT_SETTING, + MergeSchedulerConfig.AUTO_THROTTLE_SETTING, + MergeSchedulerConfig.MAX_MERGE_COUNT_SETTING, + MergeSchedulerConfig.MAX_THREAD_COUNT_SETTING, + EngineConfig.INDEX_CODEC_SETTING); static Settings filter(Settings originalSettings) { Settings.Builder settings = Settings.builder().put(originalSettings); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/TransportXPackUsageAction.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/TransportXPackUsageAction.java index 337c2281d5579..dd1b73415b541 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/TransportXPackUsageAction.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/TransportXPackUsageAction.java @@ -38,7 +38,7 @@ public TransportXPackUsageAction(ThreadPool threadPool, TransportService transpo IndexNameExpressionResolver indexNameExpressionResolver, Set featureSets) { super(XPackUsageAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, XPackUsageRequest::new); - this.featureSets = Collections.unmodifiableList(new ArrayList<>(featureSets)); + this.featureSets = List.copyOf(featureSets); } @Override diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsAction.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsAction.java index d91f7a1a06964..bee39ba88ee68 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsAction.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/dataframe/action/GetDataFrameTransformsStatsAction.java @@ -25,7 +25,6 @@ import org.elasticsearch.xpack.core.dataframe.transforms.DataFrameTransformStateAndStats; import java.io.IOException; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -84,7 +83,7 @@ public List getExpandedIds() { } public void setExpandedIds(List expandedIds) { - this.expandedIds = Collections.unmodifiableList(new ArrayList<>(expandedIds)); + this.expandedIds = List.copyOf(expandedIds); } public final void setPageParams(PageParams pageParams) { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/filestructurefinder/FileStructure.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/filestructurefinder/FileStructure.java index acaceace0472b..31098223d4b7b 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/filestructurefinder/FileStructure.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/filestructurefinder/FileStructure.java @@ -15,7 +15,6 @@ import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; -import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -179,22 +178,20 @@ public FileStructure(int numLinesAnalyzed, int numMessagesAnalyzed, String sampl this.format = Objects.requireNonNull(format); this.multilineStartPattern = multilineStartPattern; this.excludeLinesPattern = excludeLinesPattern; - this.columnNames = (columnNames == null) ? null : Collections.unmodifiableList(new ArrayList<>(columnNames)); + this.columnNames = (columnNames == null) ? null : List.copyOf(columnNames); this.hasHeaderRow = hasHeaderRow; this.delimiter = delimiter; this.quote = quote; this.shouldTrimFields = shouldTrimFields; this.grokPattern = grokPattern; this.timestampField = timestampField; - this.jodaTimestampFormats = - (jodaTimestampFormats == null) ? null : Collections.unmodifiableList(new ArrayList<>(jodaTimestampFormats)); - this.javaTimestampFormats = - (javaTimestampFormats == null) ? null : Collections.unmodifiableList(new ArrayList<>(javaTimestampFormats)); + this.jodaTimestampFormats = (jodaTimestampFormats == null) ? null : List.copyOf(jodaTimestampFormats); + this.javaTimestampFormats = (javaTimestampFormats == null) ? null : List.copyOf(javaTimestampFormats); this.needClientTimezone = needClientTimezone; this.mappings = Collections.unmodifiableSortedMap(new TreeMap<>(mappings)); this.ingestPipeline = (ingestPipeline == null) ? null : Collections.unmodifiableMap(new LinkedHashMap<>(ingestPipeline)); this.fieldStats = Collections.unmodifiableSortedMap(new TreeMap<>(fieldStats)); - this.explanation = Collections.unmodifiableList(new ArrayList<>(explanation)); + this.explanation = List.copyOf(explanation); } public FileStructure(StreamInput in) throws IOException { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/DeletePrivilegesResponse.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/DeletePrivilegesResponse.java index 18efb2ac5fac3..45ca0509f5f9b 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/DeletePrivilegesResponse.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/DeletePrivilegesResponse.java @@ -14,7 +14,6 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Set; /** @@ -29,7 +28,7 @@ public DeletePrivilegesResponse() { } public DeletePrivilegesResponse(Collection found) { - this.found = Collections.unmodifiableSet(new HashSet<>(found)); + this.found = Set.copyOf(found); } @Override diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/PutPrivilegesRequest.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/PutPrivilegesRequest.java index 651c695db6a41..62027045b116c 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/PutPrivilegesRequest.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/PutPrivilegesRequest.java @@ -16,7 +16,6 @@ import org.elasticsearch.xpack.core.security.support.MetadataUtils; import java.io.IOException; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -96,7 +95,7 @@ public List getPrivileges() { } public void setPrivileges(Collection privileges) { - this.privileges = Collections.unmodifiableList(new ArrayList<>(privileges)); + this.privileges = List.copyOf(privileges); } @Override diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java index b88056a4f24e7..7c87198b96446 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/oidc/OpenIdConnectRealmSettings.java @@ -29,9 +29,9 @@ public class OpenIdConnectRealmSettings { private OpenIdConnectRealmSettings() { } - private static final List SUPPORTED_SIGNATURE_ALGORITHMS = Collections.unmodifiableList( - Arrays.asList("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512")); - private static final List RESPONSE_TYPES = Arrays.asList("code", "id_token", "id_token token"); + private static final List SUPPORTED_SIGNATURE_ALGORITHMS = + List.of("HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512"); + private static final List RESPONSE_TYPES = List.of("code", "id_token", "id_token token"); public static final String TYPE = "oidc"; public static final Setting.AffixSetting RP_CLIENT_ID diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/ApplicationPermission.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/ApplicationPermission.java index da6af4ec7cbdc..79f751140beb8 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/ApplicationPermission.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/ApplicationPermission.java @@ -15,7 +15,6 @@ import org.elasticsearch.xpack.core.security.authz.privilege.ApplicationPrivilegeDescriptor; import org.elasticsearch.xpack.core.security.support.Automatons; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -54,7 +53,7 @@ public final class ApplicationPermission { Automatons.unionAndMinimize(Arrays.asList(existing.resourceAutomaton, patterns))); } })); - this.permissions = Collections.unmodifiableList(new ArrayList<>(permissionsByPrivilege.values())); + this.permissions = List.copyOf(permissionsByPrivilege.values()); } /** diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java index 3611b6663a38f..fa5ec665043ae 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java @@ -37,8 +37,8 @@ import java.net.Socket; import java.security.GeneralSecurityException; import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -327,7 +327,7 @@ public Set getTransportProfileContextNames() { * Accessor to the loaded ssl configuration objects at the current point in time. This is useful for testing */ Collection getLoadedSSLConfigurations() { - return Collections.unmodifiableSet(new HashSet<>(sslContexts.keySet())); + return Set.copyOf(sslContexts.keySet()); } /** diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherParams.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherParams.java index a530108a6fae6..007fcc30c3d24 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherParams.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/xcontent/WatcherParams.java @@ -12,7 +12,6 @@ import java.util.Map; import static java.util.Collections.emptyMap; -import static java.util.Collections.unmodifiableMap; public class WatcherParams extends ToXContent.DelegatingMapParams { @@ -99,7 +98,7 @@ public Builder put(String key, Object value) { } public WatcherParams build() { - return new WatcherParams(unmodifiableMap(new HashMap<>(params)), delegate); + return new WatcherParams(Map.copyOf(params), delegate); } } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/deprecation/DeprecationInfoActionResponseTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/deprecation/DeprecationInfoActionResponseTests.java index 2eff0384b6f92..94661819e5008 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/deprecation/DeprecationInfoActionResponseTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/deprecation/DeprecationInfoActionResponseTests.java @@ -24,7 +24,6 @@ import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfigTests; import java.io.IOException; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -86,18 +85,10 @@ public void testFrom() throws IOException { boolean indexIssueFound = randomBoolean(); boolean mlIssueFound = randomBoolean(); DeprecationIssue foundIssue = DeprecationIssueTests.createTestInstance(); - List> clusterSettingsChecks = - Collections.unmodifiableList(Arrays.asList( - (s) -> clusterIssueFound ? foundIssue : null - )); - List> indexSettingsChecks = - Collections.unmodifiableList(Arrays.asList( - (idx) -> indexIssueFound ? foundIssue : null - )); + List> clusterSettingsChecks = List.of((s) -> clusterIssueFound ? foundIssue : null); + List> indexSettingsChecks = List.of((idx) -> indexIssueFound ? foundIssue : null); List> mlSettingsChecks = - Collections.unmodifiableList(Arrays.asList( - (idx, unused) -> mlIssueFound ? foundIssue : null - )); + List.of((idx, unused) -> mlIssueFound ? foundIssue : null); NodesDeprecationCheckResponse nodeDeprecationIssues = new NodesDeprecationCheckResponse( new ClusterName(randomAlphaOfLength(5)), diff --git a/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/Deprecation.java b/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/Deprecation.java index 9bfbe352f839a..5b87f4153cbba 100644 --- a/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/Deprecation.java +++ b/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/Deprecation.java @@ -21,7 +21,6 @@ import org.elasticsearch.xpack.core.deprecation.DeprecationInfoAction; import org.elasticsearch.xpack.core.deprecation.NodesDeprecationCheckAction; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Supplier; @@ -30,12 +29,12 @@ * The plugin class for the Deprecation API */ public class Deprecation extends Plugin implements ActionPlugin { + @Override public List> getActions() { - return Collections.unmodifiableList(Arrays.asList( - new ActionHandler<>(DeprecationInfoAction.INSTANCE, TransportDeprecationInfoAction.class), - new ActionHandler<>(NodesDeprecationCheckAction.INSTANCE, TransportNodeDeprecationCheckAction.class) - )); + return List.of( + new ActionHandler<>(DeprecationInfoAction.INSTANCE, TransportDeprecationInfoAction.class), + new ActionHandler<>(NodesDeprecationCheckAction.INSTANCE, TransportNodeDeprecationCheckAction.class)); } @Override diff --git a/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/DeprecationChecks.java b/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/DeprecationChecks.java index 5567956c3e9a0..88ce82729df10 100644 --- a/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/DeprecationChecks.java +++ b/x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/DeprecationChecks.java @@ -14,7 +14,6 @@ import org.elasticsearch.xpack.core.deprecation.DeprecationIssue; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -34,20 +33,13 @@ private DeprecationChecks() { static List> CLUSTER_SETTINGS_CHECKS = Collections.emptyList(); - static List> NODE_SETTINGS_CHECKS = - Collections.unmodifiableList(Arrays.asList( - // STUB - )); + static List> NODE_SETTINGS_CHECKS = Collections.emptyList(); static List> INDEX_SETTINGS_CHECKS = - Collections.unmodifiableList(Arrays.asList( - IndexDeprecationChecks::oldIndicesCheck)); + Collections.singletonList(IndexDeprecationChecks::oldIndicesCheck); static List> ML_SETTINGS_CHECKS = - Collections.unmodifiableList(Arrays.asList( - MlDeprecationChecks::checkDataFeedAggregations, - MlDeprecationChecks::checkDataFeedQuery - )); + List.of(MlDeprecationChecks::checkDataFeedAggregations, MlDeprecationChecks::checkDataFeedQuery); /** * helper utility function to reduce repeat of running a specific {@link List} of checks. diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MachineLearning.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MachineLearning.java index 281a374b97b2f..1ff478782a8e8 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MachineLearning.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MachineLearning.java @@ -323,18 +323,18 @@ public static boolean isMlNode(DiscoveryNode node) { } public List> getSettings() { - return Collections.unmodifiableList( - Arrays.asList(MachineLearningField.AUTODETECT_PROCESS, - ML_ENABLED, - CONCURRENT_JOB_ALLOCATIONS, - MachineLearningField.MAX_MODEL_MEMORY_LIMIT, - MAX_LAZY_ML_NODES, - MAX_MACHINE_MEMORY_PERCENT, - AutodetectBuilder.DONT_PERSIST_MODEL_STATE_SETTING, - AutodetectBuilder.MAX_ANOMALY_RECORDS_SETTING_DYNAMIC, - MAX_OPEN_JOBS_PER_NODE, - AutodetectProcessManager.MIN_DISK_SPACE_OFF_HEAP, - MlConfigMigrationEligibilityCheck.ENABLE_CONFIG_MIGRATION)); + return List.of( + MachineLearningField.AUTODETECT_PROCESS, + ML_ENABLED, + CONCURRENT_JOB_ALLOCATIONS, + MachineLearningField.MAX_MODEL_MEMORY_LIMIT, + MAX_LAZY_ML_NODES, + MAX_MACHINE_MEMORY_PERCENT, + AutodetectBuilder.DONT_PERSIST_MODEL_STATE_SETTING, + AutodetectBuilder.MAX_ANOMALY_RECORDS_SETTING_DYNAMIC, + MAX_OPEN_JOBS_PER_NODE, + AutodetectProcessManager.MIN_DISK_SPACE_OFF_HEAP, + MlConfigMigrationEligibilityCheck.ENABLE_CONFIG_MIGRATION); } public Settings additionalSettings() { diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureFinderManager.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureFinderManager.java index 5332f18e9f05a..1a0e41c5e135e 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureFinderManager.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureFinderManager.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Objects; @@ -44,45 +43,244 @@ public final class FileStructureFinderManager { public static final int MIN_SAMPLE_LINE_COUNT = 2; public static final int DEFAULT_IDEAL_SAMPLE_LINE_COUNT = 1000; - static final Set FILEBEAT_SUPPORTED_ENCODINGS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - "866", "ansi_x3.4-1968", "arabic", "ascii", "asmo-708", "big5", "big5-hkscs", "chinese", "cn-big5", "cp1250", "cp1251", "cp1252", - "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "cp819", "cp866", "csbig5", "cseuckr", "cseucpkdfmtjapanese", - "csgb2312", "csibm866", "csiso2022jp", "csiso2022kr", "csiso58gb231280", "csiso88596e", "csiso88596i", "csiso88598e", "csiso88598i", - "csisolatin1", "csisolatin2", "csisolatin3", "csisolatin4", "csisolatin5", "csisolatin6", "csisolatin9", "csisolatinarabic", - "csisolatincyrillic", "csisolatingreek", "csisolatinhebrew", "cskoi8r", "csksc56011987", "csmacintosh", "csshiftjis", "cyrillic", - "dos-874", "ecma-114", "ecma-118", "elot_928", "euc-jp", "euc-kr", "gb18030", "gb2312", "gb_2312", "gb_2312-80", "gbk", "greek", - "greek8", "hebrew", "hz-gb-2312", "ibm819", "ibm866", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-jp", "iso-2022-kr", "iso-8859-1", - "iso-8859-10", "iso-8859-11", "iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "iso-8859-2", "iso-8859-3", "iso-8859-4", - "iso-8859-5", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-8859-7", "iso-8859-8", "iso-8859-8-e", "iso-8859-8-i", - "iso-8859-9", "iso-ir-100", "iso-ir-101", "iso-ir-109", "iso-ir-110", "iso-ir-126", "iso-ir-127", "iso-ir-138", "iso-ir-144", - "iso-ir-148", "iso-ir-149", "iso-ir-157", "iso-ir-58", "iso8859-1", "iso8859-10", "iso8859-11", "iso8859-13", "iso8859-14", - "iso8859-15", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5", "iso8859-6", "iso8859-6e", "iso8859-6i", "iso8859-7", "iso8859-8", - "iso8859-8e", "iso8859-8i", "iso8859-9", "iso88591", "iso885910", "iso885911", "iso885913", "iso885914", "iso885915", "iso88592", - "iso88593", "iso88594", "iso88595", "iso88596", "iso88597", "iso88598", "iso88599", "iso_8859-1", "iso_8859-15", "iso_8859-1:1987", - "iso_8859-2", "iso_8859-2:1987", "iso_8859-3", "iso_8859-3:1988", "iso_8859-4", "iso_8859-4:1988", "iso_8859-5", "iso_8859-5:1988", - "iso_8859-6", "iso_8859-6:1987", "iso_8859-7", "iso_8859-7:1987", "iso_8859-8", "iso_8859-8:1988", "iso_8859-9", "iso_8859-9:1989", - "koi", "koi8", "koi8-r", "koi8-ru", "koi8-u", "koi8_r", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "l1", - "l2", "l3", "l4", "l5", "l6", "l9", "latin1", "latin2", "latin3", "latin4", "latin5", "latin6", "logical", "mac", "macintosh", - "ms932", "ms_kanji", "shift-jis", "shift_jis", "sjis", "sun_eu_greek", "tis-620", "unicode-1-1-utf-8", "us-ascii", "utf-16", - "utf-16-bom", "utf-16be", "utf-16be-bom", "utf-16le", "utf-16le-bom", "utf-8", "utf8", "visual", "windows-1250", "windows-1251", - "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "windows-31j", - "windows-874", "windows-949", "x-cp1250", "x-cp1251", "x-cp1252", "x-cp1253", "x-cp1254", "x-cp1255", "x-cp1256", "x-cp1257", - "x-cp1258", "x-euc-jp", "x-gbk", "x-mac-cyrillic", "x-mac-roman", "x-mac-ukrainian", "x-sjis", "x-x-big5" - ))); + static final Set FILEBEAT_SUPPORTED_ENCODINGS = Set.of( + "866", + "ansi_x3.4-1968", + "arabic", + "ascii", + "asmo-708", + "big5", + "big5-hkscs", + "chinese", + "cn-big5", + "cp1250", + "cp1251", + "cp1252", + "cp1253", + "cp1254", + "cp1255", + "cp1256", + "cp1257", + "cp1258", + "cp819", + "cp866", + "csbig5", + "cseuckr", + "cseucpkdfmtjapanese", + "csgb2312", + "csibm866", + "csiso2022jp", + "csiso2022kr", + "csiso58gb231280", + "csiso88596e", + "csiso88596i", + "csiso88598e", + "csiso88598i", + "csisolatin1", + "csisolatin2", + "csisolatin3", + "csisolatin4", + "csisolatin5", + "csisolatin6", + "csisolatin9", + "csisolatinarabic", + "csisolatincyrillic", + "csisolatingreek", + "csisolatinhebrew", + "cskoi8r", + "csksc56011987", + "csmacintosh", + "csshiftjis", + "cyrillic", + "dos-874", + "ecma-114", + "ecma-118", + "elot_928", + "euc-jp", + "euc-kr", + "gb18030", + "gb2312", + "gb_2312", + "gb_2312-80", + "gbk", + "greek", + "greek8", + "hebrew", + "hz-gb-2312", + "ibm819", + "ibm866", + "iso-2022-cn", + "iso-2022-cn-ext", + "iso-2022-jp", + "iso-2022-kr", + "iso-8859-1", + "iso-8859-10", + "iso-8859-11", + "iso-8859-13", + "iso-8859-14", + "iso-8859-15", + "iso-8859-16", + "iso-8859-2", + "iso-8859-3", + "iso-8859-4", + "iso-8859-5", + "iso-8859-6", + "iso-8859-6-e", + "iso-8859-6-i", + "iso-8859-7", + "iso-8859-8", + "iso-8859-8-e", + "iso-8859-8-i", + "iso-8859-9", + "iso-ir-100", + "iso-ir-101", + "iso-ir-109", + "iso-ir-110", + "iso-ir-126", + "iso-ir-127", + "iso-ir-138", + "iso-ir-144", + "iso-ir-148", + "iso-ir-149", + "iso-ir-157", + "iso-ir-58", + "iso8859-1", + "iso8859-10", + "iso8859-11", + "iso8859-13", + "iso8859-14", + "iso8859-15", + "iso8859-2", + "iso8859-3", + "iso8859-4", + "iso8859-5", + "iso8859-6", + "iso8859-6e", + "iso8859-6i", + "iso8859-7", + "iso8859-8", + "iso8859-8e", + "iso8859-8i", + "iso8859-9", + "iso88591", + "iso885910", + "iso885911", + "iso885913", + "iso885914", + "iso885915", + "iso88592", + "iso88593", + "iso88594", + "iso88595", + "iso88596", + "iso88597", + "iso88598", + "iso88599", + "iso_8859-1", + "iso_8859-15", + "iso_8859-1:1987", + "iso_8859-2", + "iso_8859-2:1987", + "iso_8859-3", + "iso_8859-3:1988", + "iso_8859-4", + "iso_8859-4:1988", + "iso_8859-5", + "iso_8859-5:1988", + "iso_8859-6", + "iso_8859-6:1987", + "iso_8859-7", + "iso_8859-7:1987", + "iso_8859-8", + "iso_8859-8:1988", + "iso_8859-9", + "iso_8859-9:1989", + "koi", + "koi8", + "koi8-r", + "koi8-ru", + "koi8-u", + "koi8_r", + "korean", + "ks_c_5601-1987", + "ks_c_5601-1989", + "ksc5601", + "ksc_5601", + "l1", + "l2", + "l3", + "l4", + "l5", + "l6", + "l9", + "latin1", + "latin2", + "latin3", + "latin4", + "latin5", + "latin6", + "logical", + "mac", + "macintosh", + "ms932", + "ms_kanji", + "shift-jis", + "shift_jis", + "sjis", + "sun_eu_greek", + "tis-620", + "unicode-1-1-utf-8", + "us-ascii", + "utf-16", + "utf-16-bom", + "utf-16be", + "utf-16be-bom", + "utf-16le", + "utf-16le-bom", + "utf-8", + "utf8", + "visual", + "windows-1250", + "windows-1251", + "windows-1252", + "windows-1253", + "windows-1254", + "windows-1255", + "windows-1256", + "windows-1257", + "windows-1258", + "windows-31j", + "windows-874", + "windows-949", + "x-cp1250", + "x-cp1251", + "x-cp1252", + "x-cp1253", + "x-cp1254", + "x-cp1255", + "x-cp1256", + "x-cp1257", + "x-cp1258", + "x-euc-jp", + "x-gbk", + "x-mac-cyrillic", + "x-mac-roman", + "x-mac-ukrainian", + "x-sjis", + "x-x-big5"); /** * These need to be ordered so that the more generic formats come after the more specific ones */ - private static final List ORDERED_STRUCTURE_FACTORIES = Collections.unmodifiableList(Arrays.asList( - new NdJsonFileStructureFinderFactory(), - new XmlFileStructureFinderFactory(), - // NDJSON will often also be valid (although utterly weird) CSV, so NDJSON must come before CSV - new DelimitedFileStructureFinderFactory(',', '"', 2, false), - new DelimitedFileStructureFinderFactory('\t', '"', 2, false), - new DelimitedFileStructureFinderFactory(';', '"', 4, false), - new DelimitedFileStructureFinderFactory('|', '"', 5, true), - new TextLogFileStructureFinderFactory() - )); + private static final List ORDERED_STRUCTURE_FACTORIES = List.of( + // NDJSON will often also be valid (although utterly weird) CSV, so NDJSON must come before CSV + new NdJsonFileStructureFinderFactory(), + new XmlFileStructureFinderFactory(), + new DelimitedFileStructureFinderFactory(',', '"', 2, false), + new DelimitedFileStructureFinderFactory('\t', '"', 2, false), + new DelimitedFileStructureFinderFactory(';', '"', 4, false), + new DelimitedFileStructureFinderFactory('|', '"', 5, true), + new TextLogFileStructureFinderFactory()); private static final int BUFFER_SIZE = 8192; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureOverrides.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureOverrides.java index e30699c69b7f8..bf80c1076896f 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureOverrides.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureOverrides.java @@ -8,8 +8,6 @@ import org.elasticsearch.xpack.core.ml.action.FindFileStructureAction; import org.elasticsearch.xpack.core.ml.filestructurefinder.FileStructure; -import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -48,7 +46,7 @@ private FileStructureOverrides(String charset, FileStructure.Format format, List String timestampFormat, String timestampField) { this.charset = charset; this.format = format; - this.columnNames = (columnNames == null) ? null : Collections.unmodifiableList(new ArrayList<>(columnNames)); + this.columnNames = (columnNames == null) ? null : List.copyOf(columnNames); this.hasHeaderRow = hasHeaderRow; this.delimiter = delimiter; this.quote = quote; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/persistence/JobConfigProvider.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/persistence/JobConfigProvider.java index 64c6583f7c2df..585b4d1f87dfa 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/persistence/JobConfigProvider.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/persistence/JobConfigProvider.java @@ -70,7 +70,6 @@ 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; @@ -95,12 +94,7 @@ public class JobConfigProvider { private static final Logger logger = LogManager.getLogger(JobConfigProvider.class); - public static final Map TO_XCONTENT_PARAMS; - static { - Map modifiable = new HashMap<>(); - modifiable.put(ToXContentParams.FOR_INTERNAL_STORAGE, "true"); - TO_XCONTENT_PARAMS = Collections.unmodifiableMap(modifiable); - } + public static final Map TO_XCONTENT_PARAMS = Collections.singletonMap(ToXContentParams.FOR_INTERNAL_STORAGE, "true"); private final Client client; private final NamedXContentRegistry xContentRegistry; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java index 5af9c53649853..1b07d6cff8352 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java @@ -63,7 +63,7 @@ private synchronized void execute(T previousValue, ActionListener> liste collectedResponses.add(previousValue); if (continuationPredicate.test(previousValue)) { if (tasks.isEmpty()) { - listener.onResponse(Collections.unmodifiableList(new ArrayList<>(collectedResponses))); + listener.onResponse(List.copyOf(collectedResponses)); return; } ChainTask task = tasks.pop(); @@ -83,7 +83,7 @@ protected void doRun() { } }); } else { - listener.onResponse(Collections.unmodifiableList(new ArrayList<>(collectedResponses))); + listener.onResponse(List.copyOf(collectedResponses)); } } @@ -120,6 +120,6 @@ protected void doRun() { } public synchronized List getCollectedResponses() { - return Collections.unmodifiableList(new ArrayList<>(collectedResponses)); + return List.copyOf(collectedResponses); } } diff --git a/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/Monitoring.java b/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/Monitoring.java index b054eca1cc319..e2b137bd95d19 100644 --- a/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/Monitoring.java +++ b/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/Monitoring.java @@ -191,6 +191,6 @@ public List> getSettings() { @Override public List getSettingsFilter() { final String exportersKey = "xpack.monitoring.exporters."; - return Collections.unmodifiableList(Arrays.asList(exportersKey + "*.auth.*", exportersKey + "*.ssl.*")); + return List.of(exportersKey + "*.auth.*", exportersKey + "*.ssl.*"); } } diff --git a/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/rest/action/RestMonitoringBulkAction.java b/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/rest/action/RestMonitoringBulkAction.java index 434b0bd9fa0ff..0a1576393ba26 100644 --- a/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/rest/action/RestMonitoringBulkAction.java +++ b/x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/rest/action/RestMonitoringBulkAction.java @@ -26,8 +26,6 @@ import java.io.IOException; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -58,11 +56,10 @@ public RestMonitoringBulkAction(Settings settings, RestController controller) { MonitoringTemplateUtils.OLD_TEMPLATE_VERSION ); - final Map> versionsMap = new HashMap<>(); - versionsMap.put(MonitoredSystem.KIBANA, allVersions); - versionsMap.put(MonitoredSystem.LOGSTASH, allVersions); - versionsMap.put(MonitoredSystem.BEATS, allVersions); - supportedApiVersions = Collections.unmodifiableMap(versionsMap); + supportedApiVersions = Map.of( + MonitoredSystem.KIBANA, allVersions, + MonitoredSystem.LOGSTASH, allVersions, + MonitoredSystem.BEATS, allVersions); } @Override diff --git a/x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/rest/RestRollupSearchAction.java b/x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/rest/RestRollupSearchAction.java index 1d9960e711f61..5481ac3a43172 100644 --- a/x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/rest/RestRollupSearchAction.java +++ b/x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/rest/RestRollupSearchAction.java @@ -16,16 +16,11 @@ import org.elasticsearch.xpack.core.rollup.action.RollupSearchAction; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.Set; public class RestRollupSearchAction extends BaseRestHandler { - private static final Set RESPONSE_PARAMS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - RestSearchAction.TYPED_KEYS_PARAM, - RestSearchAction.TOTAL_HITS_AS_INT_PARAM))); + private static final Set RESPONSE_PARAMS = Set.of(RestSearchAction.TYPED_KEYS_PARAM, RestSearchAction.TOTAL_HITS_AS_INT_PARAM); public RestRollupSearchAction(Settings settings, RestController controller) { super(settings); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/Security.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/Security.java index 8cc970ca77e4f..1275dc491578d 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/Security.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/Security.java @@ -200,7 +200,9 @@ import org.elasticsearch.xpack.security.rest.action.RestInvalidateApiKeyAction; import org.elasticsearch.xpack.security.rest.action.oauth2.RestGetTokenAction; import org.elasticsearch.xpack.security.rest.action.oauth2.RestInvalidateTokenAction; +import org.elasticsearch.xpack.security.rest.action.oidc.RestOpenIdConnectAuthenticateAction; import org.elasticsearch.xpack.security.rest.action.oidc.RestOpenIdConnectLogoutAction; +import org.elasticsearch.xpack.security.rest.action.oidc.RestOpenIdConnectPrepareAuthenticationAction; import org.elasticsearch.xpack.security.rest.action.privilege.RestDeletePrivilegesAction; import org.elasticsearch.xpack.security.rest.action.privilege.RestGetPrivilegesAction; import org.elasticsearch.xpack.security.rest.action.privilege.RestPutPrivilegesAction; @@ -212,8 +214,6 @@ import org.elasticsearch.xpack.security.rest.action.rolemapping.RestDeleteRoleMappingAction; import org.elasticsearch.xpack.security.rest.action.rolemapping.RestGetRoleMappingsAction; import org.elasticsearch.xpack.security.rest.action.rolemapping.RestPutRoleMappingAction; -import org.elasticsearch.xpack.security.rest.action.oidc.RestOpenIdConnectAuthenticateAction; -import org.elasticsearch.xpack.security.rest.action.oidc.RestOpenIdConnectPrepareAuthenticationAction; import org.elasticsearch.xpack.security.rest.action.saml.RestSamlAuthenticateAction; import org.elasticsearch.xpack.security.rest.action.saml.RestSamlInvalidateSessionAction; import org.elasticsearch.xpack.security.rest.action.saml.RestSamlLogoutAction; @@ -894,13 +894,31 @@ public Map> getTransports(Settings settings, ThreadP } IPFilter ipFilter = this.ipFilter.get(); - Map> transports = new HashMap<>(); - transports.put(SecurityField.NAME4, () -> new SecurityNetty4ServerTransport(settings, Version.CURRENT, threadPool, - networkService, pageCacheRecycler, namedWriteableRegistry, circuitBreakerService, ipFilter, getSslService())); - transports.put(SecurityField.NIO, () -> new SecurityNioTransport(settings, Version.CURRENT, threadPool, networkService, - pageCacheRecycler, namedWriteableRegistry, circuitBreakerService, ipFilter, getSslService(), getNioGroupFactory(settings))); - - return Collections.unmodifiableMap(transports); + return Map.of( + // security based on Netty 4 + SecurityField.NAME4, + () -> new SecurityNetty4ServerTransport( + settings, + Version.CURRENT, + threadPool, + networkService, + pageCacheRecycler, + namedWriteableRegistry, + circuitBreakerService, + ipFilter, + getSslService()), + // security based on NIO + SecurityField.NIO, + () -> new SecurityNioTransport(settings, + Version.CURRENT, + threadPool, + networkService, + pageCacheRecycler, + namedWriteableRegistry, + circuitBreakerService, + ipFilter, + getSslService(), + getNioGroupFactory(settings))); } @Override diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java index 66206d5013713..3a27b6670aeb1 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/InternalRealms.java @@ -37,7 +37,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -102,23 +101,35 @@ public static Map getFactories(ThreadPool threadPool, Res NativeRoleMappingStore nativeRoleMappingStore, SecurityIndexManager securityIndex) { - Map map = new HashMap<>(); - map.put(FileRealmSettings.TYPE, config -> new FileRealm(config, resourceWatcherService, threadPool)); - map.put(NativeRealmSettings.TYPE, config -> { - final NativeRealm nativeRealm = new NativeRealm(config, nativeUsersStore, threadPool); - securityIndex.addIndexStateListener(nativeRealm::onSecurityIndexStateChange); - return nativeRealm; - }); - map.put(LdapRealmSettings.AD_TYPE, config -> new LdapRealm(config, sslService, - resourceWatcherService, nativeRoleMappingStore, threadPool)); - map.put(LdapRealmSettings.LDAP_TYPE, config -> new LdapRealm(config, - sslService, resourceWatcherService, nativeRoleMappingStore, threadPool)); - map.put(PkiRealmSettings.TYPE, config -> new PkiRealm(config, resourceWatcherService, nativeRoleMappingStore)); - map.put(SamlRealmSettings.TYPE, config -> SamlRealm.create(config, sslService, resourceWatcherService, nativeRoleMappingStore)); - map.put(KerberosRealmSettings.TYPE, config -> new KerberosRealm(config, nativeRoleMappingStore, threadPool)); - map.put(OpenIdConnectRealmSettings.TYPE, config -> new OpenIdConnectRealm(config, sslService, nativeRoleMappingStore, - resourceWatcherService)); - return Collections.unmodifiableMap(map); + return Map.of( + // file realm + FileRealmSettings.TYPE, + config -> new FileRealm(config, resourceWatcherService, threadPool), + // native realm + NativeRealmSettings.TYPE, + config -> { + final NativeRealm nativeRealm = new NativeRealm(config, nativeUsersStore, threadPool); + securityIndex.addIndexStateListener(nativeRealm::onSecurityIndexStateChange); + return nativeRealm; + }, + // active directory realm + LdapRealmSettings.AD_TYPE, + config -> new LdapRealm(config, sslService, resourceWatcherService, nativeRoleMappingStore, threadPool), + // LDAP realm + LdapRealmSettings.LDAP_TYPE, + config -> new LdapRealm(config, sslService, resourceWatcherService, nativeRoleMappingStore, threadPool), + // PKI realm + PkiRealmSettings.TYPE, + config -> new PkiRealm(config, resourceWatcherService, nativeRoleMappingStore), + // SAML realm + SamlRealmSettings.TYPE, + config -> SamlRealm.create(config, sslService, resourceWatcherService, nativeRoleMappingStore), + // Kerberos realm + KerberosRealmSettings.TYPE, + config -> new KerberosRealm(config, nativeRoleMappingStore, threadPool), + // OpenID Connect realm + OpenIdConnectRealmSettings.TYPE, + config -> new OpenIdConnectRealm(config, sslService, nativeRoleMappingStore, resourceWatcherService)); } private InternalRealms() { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTicketValidator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTicketValidator.java index 9f2a182839857..f24aaedcbf71d 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTicketValidator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosTicketValidator.java @@ -6,8 +6,8 @@ package org.elasticsearch.xpack.security.authc.kerberos; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.collect.Tuple; @@ -17,21 +17,20 @@ import org.ietf.jgss.GSSManager; import org.ietf.jgss.Oid; +import javax.security.auth.Subject; +import javax.security.auth.login.AppConfigurationEntry; +import javax.security.auth.login.Configuration; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Base64; import java.util.Collections; -import java.util.HashMap; import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.Configuration; -import javax.security.auth.login.LoginContext; -import javax.security.auth.login.LoginException; - /** * Utility class that validates kerberos ticket for peer authentication. *

@@ -254,21 +253,18 @@ static class KeytabJaasConf extends Configuration { @Override public AppConfigurationEntry[] getAppConfigurationEntry(final String name) { - final Map options = new HashMap<>(); - options.put("keyTab", keytabFilePath); - /* - * As acceptor, we can have multiple SPNs, we do not want to use particular - * principal so it uses "*" - */ - options.put("principal", "*"); - options.put("useKeyTab", Boolean.TRUE.toString()); - options.put("storeKey", Boolean.TRUE.toString()); - options.put("doNotPrompt", Boolean.TRUE.toString()); - options.put("isInitiator", Boolean.FALSE.toString()); - options.put("debug", Boolean.toString(krbDebug)); - - return new AppConfigurationEntry[] { new AppConfigurationEntry(SUN_KRB5_LOGIN_MODULE, - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Collections.unmodifiableMap(options)) }; + return new AppConfigurationEntry[]{new AppConfigurationEntry( + SUN_KRB5_LOGIN_MODULE, + AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, + Map.of( + "keyTab", keytabFilePath, + // as acceptor, we can have multiple SPNs, we do not want to use any particular principal so it uses "*" + "principal", "*", + "useKeyTab", Boolean.TRUE.toString(), + "storeKey", Boolean.TRUE.toString(), + "doNotPrompt", Boolean.TRUE.toString(), + "isInitiator", Boolean.FALSE.toString(), + "debug", Boolean.toString(krbDebug)))}; } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/UserAttributeGroupsResolver.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/UserAttributeGroupsResolver.java index d2b2a346a9588..32e7cf890a322 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/UserAttributeGroupsResolver.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/UserAttributeGroupsResolver.java @@ -56,7 +56,7 @@ public void resolve(LDAPInterface connection, String userDn, TimeValue timeout, if (entry == null || entry.hasAttribute(attribute) == false) { listener.onResponse(Collections.emptyList()); } else { - listener.onResponse(Collections.unmodifiableList(Arrays.asList(entry.getAttributeValues(attribute)))); + listener.onResponse(List.of(entry.getAttributeValues(attribute))); } }, listener::onFailure), attribute); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/DnRoleMapper.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/DnRoleMapper.java index 78094f518c53c..1018c591617a9 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/DnRoleMapper.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/DnRoleMapper.java @@ -5,25 +5,10 @@ */ package org.elasticsearch.xpack.security.authc.support; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -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; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.stream.Collectors; - import com.unboundid.ldap.sdk.DN; import com.unboundid.ldap.sdk.LDAPException; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.elasticsearch.ElasticsearchException; @@ -37,6 +22,20 @@ import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.support.DnRoleMapperSettings; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Collectors; + import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.xpack.security.authc.ldap.support.LdapUtils.dn; @@ -153,7 +152,7 @@ public static Map> parseFile(Path path, Logger logger, Stri realmName); Map> normalizedMap = dnToRoles.entrySet().stream().collect(Collectors.toMap( entry -> entry.getKey().toNormalizedString(), - entry -> Collections.unmodifiableList(new ArrayList<>(entry.getValue())))); + entry -> List.copyOf(entry.getValue()))); return unmodifiableMap(normalizedMap); } catch (IOException | SettingsException e) { throw new ElasticsearchException("could not read realm [" + realmType + "/" + realmName + "] role mappings file [" + diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java index dbc323810610f..107b578cc0161 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java @@ -21,7 +21,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -63,7 +62,7 @@ public UserData(String username, @Nullable String dn, Collection groups, this.username = username; this.dn = dn; this.groups = groups == null || groups.isEmpty() - ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(groups)); + ? Collections.emptySet() : Set.copyOf(groups); this.metadata = metadata == null || metadata.isEmpty() ? Collections.emptyMap() : Collections.unmodifiableMap(metadata); this.realm = realm; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java index 781072b95a254..7454ec59da55f 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java @@ -139,7 +139,7 @@ public CompositeRolesStore(Settings settings, FileRolesStore fileRolesStore, Nat nlcBuilder.setMaximumWeight(nlcCacheSize); } this.negativeLookupCache = nlcBuilder.build(); - this.builtInRoleProviders = Collections.unmodifiableList(Arrays.asList(reservedRolesStore, fileRolesStore, nativeRolesStore)); + this.builtInRoleProviders = List.of(reservedRolesStore, fileRolesStore, nativeRolesStore); if (rolesProviders.isEmpty()) { this.allRoleProviders = this.builtInRoleProviders; } else { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java index d9fac13e6a77d..58ca09da929f9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java @@ -15,32 +15,32 @@ import org.elasticsearch.xpack.sql.tree.Source; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; +import static java.util.Map.entry; + public class MatchQuery extends LeafQuery { private static final Map> BUILDER_APPLIERS; static { - HashMap> appliers = new HashMap<>(11); // TODO: it'd be great if these could be constants instead of Strings, needs a core change to make the fields public first // TODO: add zero terms query support, I'm not sure the best way to parse it yet... // appliers.put("zero_terms_query", (qb, s) -> qb.zeroTermsQuery(s)); - appliers.put("analyzer", (qb, s) -> qb.analyzer(s)); - appliers.put("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))); - appliers.put("cutoff_frequency", (qb, s) -> qb.cutoffFrequency(Float.valueOf(s))); - appliers.put("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))); - appliers.put("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))); - appliers.put("fuzzy_rewrite", (qb, s) -> qb.fuzzyRewrite(s)); - appliers.put("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))); - appliers.put("max_expansions", (qb, s) -> qb.maxExpansions(Integer.valueOf(s))); - appliers.put("minimum_should_match", (qb, s) -> qb.minimumShouldMatch(s)); - appliers.put("operator", (qb, s) -> qb.operator(Operator.fromString(s))); - appliers.put("prefix_length", (qb, s) -> qb.prefixLength(Integer.valueOf(s))); - BUILDER_APPLIERS = Collections.unmodifiableMap(appliers); + BUILDER_APPLIERS = Map.ofEntries( + entry("analyzer", MatchQueryBuilder::analyzer), + entry("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))), + entry("cutoff_frequency", (qb, s) -> qb.cutoffFrequency(Float.valueOf(s))), + entry("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))), + entry("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))), + entry("fuzzy_rewrite", MatchQueryBuilder::fuzzyRewrite), + entry("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))), + entry("max_expansions", (qb, s) -> qb.maxExpansions(Integer.valueOf(s))), + entry("minimum_should_match", MatchQueryBuilder::minimumShouldMatch), + entry("operator", (qb, s) -> qb.operator(Operator.fromString(s))), + entry("prefix_length", (qb, s) -> qb.prefixLength(Integer.valueOf(s)))); } private final String name; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java index 141dc4776a5ff..f51f8275a898c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java @@ -14,36 +14,35 @@ import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; import org.elasticsearch.xpack.sql.tree.Source; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; +import static java.util.Map.entry; + public class MultiMatchQuery extends LeafQuery { private static final Map> BUILDER_APPLIERS; static { - HashMap> appliers = new HashMap<>(14); // TODO: it'd be great if these could be constants instead of Strings, needs a core change to make the fields public first - appliers.put("slop", (qb, s) -> qb.slop(Integer.valueOf(s))); - // TODO: add zero terms query support, I'm not sure the best way to parse it yet... - // appliers.put("zero_terms_query", (qb, s) -> qb.zeroTermsQuery(s)); - appliers.put("analyzer", (qb, s) -> qb.analyzer(s)); - appliers.put("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))); - appliers.put("cutoff_frequency", (qb, s) -> qb.cutoffFrequency(Float.valueOf(s))); - appliers.put("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))); - appliers.put("fuzzy_rewrite", (qb, s) -> qb.fuzzyRewrite(s)); - appliers.put("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))); - appliers.put("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))); - appliers.put("max_expansions", (qb, s) -> qb.maxExpansions(Integer.valueOf(s))); - appliers.put("minimum_should_match", (qb, s) -> qb.minimumShouldMatch(s)); - appliers.put("operator", (qb, s) -> qb.operator(Operator.fromString(s))); - appliers.put("prefix_length", (qb, s) -> qb.prefixLength(Integer.valueOf(s))); - appliers.put("tie_breaker", (qb, s) -> qb.tieBreaker(Float.valueOf(s))); - appliers.put("type", (qb, s) -> qb.type(s)); - BUILDER_APPLIERS = Collections.unmodifiableMap(appliers); + BUILDER_APPLIERS = Map.ofEntries( + entry("slop", (qb, s) -> qb.slop(Integer.valueOf(s))), + // TODO: add zero terms query support, I'm not sure the best way to parse it yet... + // appliers.put("zero_terms_query", (qb, s) -> qb.zeroTermsQuery(s)); + entry("analyzer", MultiMatchQueryBuilder::analyzer), + entry("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))), + entry("cutoff_frequency", (qb, s) -> qb.cutoffFrequency(Float.valueOf(s))), + entry("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))), + entry("fuzzy_rewrite", MultiMatchQueryBuilder::fuzzyRewrite), + entry("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))), + entry("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))), + entry("max_expansions", (qb, s) -> qb.maxExpansions(Integer.valueOf(s))), + entry("minimum_should_match", MultiMatchQueryBuilder::minimumShouldMatch), + entry("operator", (qb, s) -> qb.operator(Operator.fromString(s))), + entry("prefix_length", (qb, s) -> qb.prefixLength(Integer.valueOf(s))), + entry("tie_breaker", (qb, s) -> qb.tieBreaker(Float.valueOf(s))), + entry("type", MultiMatchQueryBuilder::type)); } private final String query; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java index 94a9716b7cc8a..a81d1d1c9dae7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java @@ -17,43 +17,39 @@ import org.elasticsearch.xpack.sql.tree.Source; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; +import static java.util.Map.entry; + public class QueryStringQuery extends LeafQuery { - private static final Map> BUILDER_APPLIERS; - - static { - HashMap> appliers = new HashMap<>(28); - // TODO: it'd be great if these could be constants instead of Strings, needs a core change to make the fields public first - appliers.put("allow_leading_wildcard", (qb, s) -> qb.allowLeadingWildcard(Booleans.parseBoolean(s))); - appliers.put("analyze_wildcard", (qb, s) -> qb.analyzeWildcard(Booleans.parseBoolean(s))); - appliers.put("analyzer", (qb, s) -> qb.analyzer(s)); - appliers.put("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))); - appliers.put("default_field", (qb, s) -> qb.defaultField(s)); - appliers.put("default_operator", (qb, s) -> qb.defaultOperator(Operator.fromString(s))); - appliers.put("enable_position_increments", (qb, s) -> qb.enablePositionIncrements(Booleans.parseBoolean(s))); - appliers.put("escape", (qb, s) -> qb.escape(Booleans.parseBoolean(s))); - appliers.put("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))); - appliers.put("fuzzy_max_expansions", (qb, s) -> qb.fuzzyMaxExpansions(Integer.valueOf(s))); - appliers.put("fuzzy_prefix_length", (qb, s) -> qb.fuzzyPrefixLength(Integer.valueOf(s))); - appliers.put("fuzzy_rewrite", (qb, s) -> qb.fuzzyRewrite(s)); - appliers.put("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))); - appliers.put("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))); - appliers.put("max_determinized_states", (qb, s) -> qb.maxDeterminizedStates(Integer.valueOf(s))); - appliers.put("minimum_should_match", (qb, s) -> qb.minimumShouldMatch(s)); - appliers.put("phrase_slop", (qb, s) -> qb.phraseSlop(Integer.valueOf(s))); - appliers.put("rewrite", (qb, s) -> qb.rewrite(s)); - appliers.put("quote_analyzer", (qb, s) -> qb.quoteAnalyzer(s)); - appliers.put("quote_field_suffix", (qb, s) -> qb.quoteFieldSuffix(s)); - appliers.put("tie_breaker", (qb, s) -> qb.tieBreaker(Float.valueOf(s))); - appliers.put("time_zone", (qb, s) -> qb.timeZone(s)); - appliers.put("type", (qb, s) -> qb.type(MultiMatchQueryBuilder.Type.parse(s, LoggingDeprecationHandler.INSTANCE))); - BUILDER_APPLIERS = Collections.unmodifiableMap(appliers); - } + // TODO: it'd be great if these could be constants instead of Strings, needs a core change to make the fields public first + private static final Map> BUILDER_APPLIERS = Map.ofEntries( + entry("allow_leading_wildcard", (qb, s) -> qb.allowLeadingWildcard(Booleans.parseBoolean(s))), + entry("analyze_wildcard", (qb, s) -> qb.analyzeWildcard(Booleans.parseBoolean(s))), + entry("analyzer", QueryStringQueryBuilder::analyzer), + entry("auto_generate_synonyms_phrase_query", (qb, s) -> qb.autoGenerateSynonymsPhraseQuery(Booleans.parseBoolean(s))), + entry("default_field", QueryStringQueryBuilder::defaultField), + entry("default_operator", (qb, s) -> qb.defaultOperator(Operator.fromString(s))), + entry("enable_position_increments", (qb, s) -> qb.enablePositionIncrements(Booleans.parseBoolean(s))), + entry("escape", (qb, s) -> qb.escape(Booleans.parseBoolean(s))), + entry("fuzziness", (qb, s) -> qb.fuzziness(Fuzziness.fromString(s))), + entry("fuzzy_max_expansions", (qb, s) -> qb.fuzzyMaxExpansions(Integer.valueOf(s))), + entry("fuzzy_prefix_length", (qb, s) -> qb.fuzzyPrefixLength(Integer.valueOf(s))), + entry("fuzzy_rewrite", QueryStringQueryBuilder::fuzzyRewrite), + entry("fuzzy_transpositions", (qb, s) -> qb.fuzzyTranspositions(Booleans.parseBoolean(s))), + entry("lenient", (qb, s) -> qb.lenient(Booleans.parseBoolean(s))), + entry("max_determinized_states", (qb, s) -> qb.maxDeterminizedStates(Integer.valueOf(s))), + entry("minimum_should_match", QueryStringQueryBuilder::minimumShouldMatch), + entry("phrase_slop", (qb, s) -> qb.phraseSlop(Integer.valueOf(s))), + entry("rewrite", QueryStringQueryBuilder::rewrite), + entry("quote_analyzer", QueryStringQueryBuilder::quoteAnalyzer), + entry("quote_field_suffix", QueryStringQueryBuilder::quoteFieldSuffix), + entry("tie_breaker", (qb, s) -> qb.tieBreaker(Float.valueOf(s))), + entry("time_zone", QueryStringQueryBuilder::timeZone), + entry("type", (qb, s) -> qb.type(MultiMatchQueryBuilder.Type.parse(s, LoggingDeprecationHandler.INSTANCE)))); private final String query; private final Map fields; diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java index f5f12d4fd244a..dd7f268e1a6f5 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java @@ -62,13 +62,11 @@ import org.elasticsearch.xpack.core.watcher.WatcherField; import org.elasticsearch.xpack.core.watcher.actions.ActionFactory; import org.elasticsearch.xpack.core.watcher.actions.ActionRegistry; -import org.elasticsearch.xpack.core.watcher.condition.ConditionFactory; import org.elasticsearch.xpack.core.watcher.condition.ConditionRegistry; import org.elasticsearch.xpack.core.watcher.crypto.CryptoService; import org.elasticsearch.xpack.core.watcher.execution.TriggeredWatchStoreField; import org.elasticsearch.xpack.core.watcher.history.HistoryStoreField; import org.elasticsearch.xpack.core.watcher.input.none.NoneInput; -import org.elasticsearch.xpack.core.watcher.transform.TransformFactory; import org.elasticsearch.xpack.core.watcher.transform.TransformRegistry; import org.elasticsearch.xpack.core.watcher.transport.actions.ack.AckWatchAction; import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchAction; @@ -291,18 +289,18 @@ public Collection createComponents(Client client, ClusterService cluster EmailAttachmentsParser emailAttachmentsParser = new EmailAttachmentsParser(emailAttachmentParsers); // conditions - final Map parsers = new HashMap<>(); - parsers.put(InternalAlwaysCondition.TYPE, (c, id, p) -> InternalAlwaysCondition.parse(id, p)); - parsers.put(NeverCondition.TYPE, (c, id, p) -> NeverCondition.parse(id, p)); - parsers.put(ArrayCompareCondition.TYPE, ArrayCompareCondition::parse); - parsers.put(CompareCondition.TYPE, CompareCondition::parse); - parsers.put(ScriptCondition.TYPE, (c, id, p) -> ScriptCondition.parse(scriptService, id, p)); - - final ConditionRegistry conditionRegistry = new ConditionRegistry(Collections.unmodifiableMap(parsers), getClock()); - final Map transformFactories = new HashMap<>(); - transformFactories.put(ScriptTransform.TYPE, new ScriptTransformFactory(scriptService)); - transformFactories.put(SearchTransform.TYPE, new SearchTransformFactory(settings, client, xContentRegistry, scriptService)); - final TransformRegistry transformRegistry = new TransformRegistry(Collections.unmodifiableMap(transformFactories)); + + final ConditionRegistry conditionRegistry = new ConditionRegistry( + Map.of( + InternalAlwaysCondition.TYPE, (c, id, p) -> InternalAlwaysCondition.parse(id, p), + NeverCondition.TYPE, (c, id, p) -> NeverCondition.parse(id, p), + ArrayCompareCondition.TYPE, ArrayCompareCondition::parse, + CompareCondition.TYPE, CompareCondition::parse, + ScriptCondition.TYPE, (c, id, p) -> ScriptCondition.parse(scriptService, id, p)), + getClock()); + final TransformRegistry transformRegistry = new TransformRegistry(Map.of( + ScriptTransform.TYPE, new ScriptTransformFactory(scriptService), + SearchTransform.TYPE, new SearchTransformFactory(settings, client, xContentRegistry, scriptService))); // actions final Map actionFactoryMap = new HashMap<>(); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/HttpRequestTemplate.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/HttpRequestTemplate.java index 8ca87395248b1..55e5d07a71c7b 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/HttpRequestTemplate.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/HttpRequestTemplate.java @@ -29,7 +29,6 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; -import static java.util.Collections.unmodifiableMap; public class HttpRequestTemplate implements ToXContentObject { @@ -469,8 +468,8 @@ public Builder proxy(HttpProxy proxy) { } public HttpRequestTemplate build() { - return new HttpRequestTemplate(host, port, scheme, method, path, unmodifiableMap(new HashMap<>(params)), - unmodifiableMap(new HashMap<>(headers)), auth, body, connectionTimeout, readTimeout, proxy); + return new HttpRequestTemplate(host, port, scheme, method, path, Map.copyOf(params), + Map.copyOf(headers), auth, body, connectionTimeout, readTimeout, proxy); } public Builder fromUrl(String supposedUrl) { diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherMockScriptPlugin.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherMockScriptPlugin.java index 5a03a3c0e6433..2515a827bcc60 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherMockScriptPlugin.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/WatcherMockScriptPlugin.java @@ -15,8 +15,6 @@ import org.elasticsearch.xpack.watcher.condition.WatcherConditionScript; import org.elasticsearch.xpack.watcher.transform.script.WatcherTransformScript; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,35 +27,31 @@ public abstract class WatcherMockScriptPlugin extends MockScriptPlugin { public static final Map, MockScriptEngine.ContextCompiler> CONTEXT_COMPILERS; static { - Map, MockScriptEngine.ContextCompiler> compilers = new HashMap<>(); - compilers.put(WatcherConditionScript.CONTEXT, (script, options) -> - (WatcherConditionScript.Factory) (params, watcherContext) -> - new WatcherConditionScript(params, watcherContext) { - @Override - public boolean execute() { - Map vars = new HashMap<>(); - vars.put("params", getParams()); - vars.put("ctx", getCtx()); - return (boolean) script.apply(vars); - } - }); - compilers.put(WatcherTransformScript.CONTEXT, (script, options) -> - (WatcherTransformScript.Factory) (params, watcherContext, payload) -> - new WatcherTransformScript(params, watcherContext, payload) { - @Override - public Object execute() { - Map vars = new HashMap<>(); - vars.put("params", getParams()); - vars.put("ctx", getCtx()); - return script.apply(vars); - } - }); - CONTEXT_COMPILERS = Collections.unmodifiableMap(compilers); + CONTEXT_COMPILERS = Map.of(WatcherConditionScript.CONTEXT, (script, options) -> + (WatcherConditionScript.Factory) (params, watcherContext) -> + new WatcherConditionScript(params, watcherContext) { + @Override + public boolean execute() { + Map vars = new HashMap<>(); + vars.put("params", getParams()); + vars.put("ctx", getCtx()); + return (boolean) script.apply(vars); + } + }, WatcherTransformScript.CONTEXT, (script, options) -> + (WatcherTransformScript.Factory) (params, watcherContext, payload) -> + new WatcherTransformScript(params, watcherContext, payload) { + @Override + public Object execute() { + Map vars = new HashMap<>(); + vars.put("params", getParams()); + vars.put("ctx", getCtx()); + return script.apply(vars); + } + }); } - public static final List> CONTEXTS = Collections.unmodifiableList(Arrays.asList( - WatcherConditionScript.CONTEXT, WatcherTransformScript.CONTEXT, Watcher.SCRIPT_TEMPLATE_CONTEXT - )); + public static final List> CONTEXTS = + List.of(WatcherConditionScript.CONTEXT, WatcherTransformScript.CONTEXT, Watcher.SCRIPT_TEMPLATE_CONTEXT); @Override protected Map, MockScriptEngine.ContextCompiler> pluginContextCompilers() { diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java index ac944755b9c4d..84144b2866b32 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java @@ -37,7 +37,6 @@ import org.elasticsearch.xpack.core.watcher.input.ExecutableInput; import org.elasticsearch.xpack.core.watcher.input.none.NoneInput; import org.elasticsearch.xpack.core.watcher.transform.ExecutableTransform; -import org.elasticsearch.xpack.core.watcher.transform.TransformFactory; import org.elasticsearch.xpack.core.watcher.transform.TransformRegistry; import org.elasticsearch.xpack.core.watcher.transform.chain.ChainTransform; import org.elasticsearch.xpack.core.watcher.transform.chain.ExecutableChainTransform; @@ -572,10 +571,11 @@ private ExecutableTransform randomTransform() { } private TransformRegistry transformRegistry() { - Map factories = new HashMap<>(); - factories.put(ScriptTransform.TYPE, new ScriptTransformFactory(scriptService)); - factories.put(SearchTransform.TYPE, new SearchTransformFactory(settings, client, xContentRegistry(), scriptService)); - return new TransformRegistry(unmodifiableMap(factories)); + return new TransformRegistry(Map.of( + ScriptTransform.TYPE, + new ScriptTransformFactory(scriptService), + SearchTransform.TYPE, + new SearchTransformFactory(settings, client, xContentRegistry(), scriptService))); } private List randomActions() { diff --git a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SpnegoClient.java b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SpnegoClient.java index 839b25c783690..42fde573c3d07 100644 --- a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SpnegoClient.java +++ b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SpnegoClient.java @@ -18,17 +18,6 @@ import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; -import java.io.IOException; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.Base64; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -40,6 +29,16 @@ import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; +import java.io.IOException; +import java.security.AccessController; +import java.security.Principal; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.Base64; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + /** * This class is used as a Spnego client during testing and handles SPNEGO * interactions using GSS context negotiation.
@@ -196,16 +195,17 @@ static class PasswordJaasConf extends Configuration { @Override public AppConfigurationEntry[] getAppConfigurationEntry(final String name) { - final Map options = new HashMap<>(); - options.put("principal", principal); - options.put("storeKey", Boolean.TRUE.toString()); - options.put("isInitiator", Boolean.TRUE.toString()); - options.put("debug", Boolean.TRUE.toString()); - // Refresh Krb5 config during tests as the port keeps changing for kdc server - options.put("refreshKrb5Config", Boolean.TRUE.toString()); - return new AppConfigurationEntry[] { new AppConfigurationEntry(SUN_KRB5_LOGIN_MODULE, - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Collections.unmodifiableMap(options)) }; + return new AppConfigurationEntry[]{new AppConfigurationEntry( + SUN_KRB5_LOGIN_MODULE, + AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, + Map.of( + "principal", principal, + "storeKey", Boolean.TRUE.toString(), + "isInitiator", Boolean.TRUE.toString(), + "debug", Boolean.TRUE.toString(), + // refresh Krb5 config during tests as the port keeps changing for kdc server + "refreshKrb5Config", Boolean.TRUE.toString()))}; } } From cdd45e896f420fa501e0ac271e8156a87c437a13 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Sun, 21 Apr 2019 13:14:24 -0400 Subject: [PATCH 02/20] Iterator --- .../ingest/common/ScriptProcessor.java | 7 +- .../common/ScriptProcessorFactoryTests.java | 4 +- .../action/PainlessExecuteAction.java | 12 +- .../plugin/store/smb/SMBStorePlugin.java | 4 +- .../common/io/stream/StreamOutput.java | 279 +++++++++++------- .../search/lookup/LeafSearchLookup.java | 6 +- .../shrink/TransportResizeActionTests.java | 10 +- .../structure/RoutingIteratorTests.java | 7 +- .../SharedClusterSnapshotRestoreIT.java | 20 +- .../xpack/ccr/action/ShardFollowNodeTask.java | 5 - 10 files changed, 211 insertions(+), 143 deletions(-) diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java index 4bbd701ff32e2..ee8d41c37c2f3 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ScriptProcessor.java @@ -38,6 +38,7 @@ import java.io.InputStream; import java.util.Arrays; +import java.util.Collections; import java.util.Map; import static org.elasticsearch.ingest.ConfigurationUtils.newConfigurationException; @@ -47,10 +48,8 @@ */ public final class ScriptProcessor extends AbstractProcessor { - private static final Map DEPRECATIONS; - static { - DEPRECATIONS = Map.of("_type", "[types removal] Looking up doc types [_type] in scripts is deprecated."); - } + private static final Map DEPRECATIONS = + Collections.singletonMap("_type", "[types removal] Looking up doc types [_type] in scripts is deprecated."); public static final String TYPE = "script"; diff --git a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java index d35ca5946e009..9559c150df68a 100644 --- a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java +++ b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ScriptProcessorFactoryTests.java @@ -41,7 +41,9 @@ public class ScriptProcessorFactoryTests extends ESTestCase { private ScriptProcessor.Factory factory; - private static final Map INGEST_SCRIPT_PARAM_TO_TYPE = Map.of("id", "stored", "source", "inline"); + private static final Map INGEST_SCRIPT_PARAM_TO_TYPE = Map.of( + "id", "stored", + "source", "inline"); @Before public void init() { diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java index e4a10d3f74478..217b5fc76588a 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java @@ -118,14 +118,10 @@ public static class Request extends SingleShardRequest implements ToXCo PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), ContextSetup::parse, CONTEXT_SETUP_FIELD); } - static final Map> SUPPORTED_CONTEXTS; - - static { - SUPPORTED_CONTEXTS = Map.of( - "painless_test", PainlessTestScript.CONTEXT, - "filter", FilterScript.CONTEXT, - "score", ScoreScript.CONTEXT); - } + static final Map> SUPPORTED_CONTEXTS = Map.of( + "painless_test", PainlessTestScript.CONTEXT, + "filter", FilterScript.CONTEXT, + "score", ScoreScript.CONTEXT); static ScriptContext fromScriptContextName(String name) { ScriptContext scriptContext = SUPPORTED_CONTEXTS.get(name); diff --git a/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java b/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java index 4093368228258..111100a2f1580 100644 --- a/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java +++ b/plugins/store-smb/src/main/java/org/elasticsearch/plugin/store/smb/SMBStorePlugin.java @@ -33,7 +33,9 @@ public class SMBStorePlugin extends Plugin implements IndexStorePlugin { @Override public Map> getIndexStoreFactories() { - return Map.of("smb_mmap_fs", SmbMmapFsIndexStore::new, "smb_simple_fs", SmbSimpleFsIndexStore::new); + return Map.of( + "smb_mmap_fs", SmbMmapFsIndexStore::new, + "smb_simple_fs", SmbSimpleFsIndexStore::new); } } diff --git a/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java b/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java index 5cd13be2c3087..64474bde7ea67 100644 --- a/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java +++ b/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java @@ -71,6 +71,8 @@ import java.util.concurrent.TimeUnit; import java.util.function.IntFunction; +import static java.util.Map.entry; + /** * A stream from another node to this node. Technically, it can also be streamed from a byte array but that is mostly for testing. * @@ -592,111 +594,178 @@ public final void writeOptionalInstant(@Nullable Instant instant) throws IOExcep } } - private static final Map, Writer> WRITERS; - - static { - WRITERS = Map.ofEntries(Map.entry(String.class, (o, v) -> { - o.writeByte((byte) 0); - o.writeString((String) v); - }), Map.entry(Integer.class, (o, v) -> { - o.writeByte((byte) 1); - o.writeInt((Integer) v); - }), Map.entry(Long.class, (o, v) -> { - o.writeByte((byte) 2); - o.writeLong((Long) v); - }), Map.entry(Float.class, (o, v) -> { - o.writeByte((byte) 3); - o.writeFloat((float) v); - }), Map.entry(Double.class, (o, v) -> { - o.writeByte((byte) 4); - o.writeDouble((double) v); - }), Map.entry(Boolean.class, (o, v) -> { - o.writeByte((byte) 5); - o.writeBoolean((boolean) v); - }), Map.entry(byte[].class, (o, v) -> { - o.writeByte((byte) 6); - final byte[] bytes = (byte[]) v; - o.writeVInt(bytes.length); - o.writeBytes(bytes); - }), Map.entry(List.class, (o, v) -> { - o.writeByte((byte) 7); - final List list = (List) v; - o.writeVInt(list.size()); - for (Object item : list) { - o.writeGenericValue(item); - } - }), Map.entry(Object[].class, (o, v) -> { - o.writeByte((byte) 8); - final Object[] list = (Object[]) v; - o.writeVInt(list.length); - for (Object item : list) { - o.writeGenericValue(item); - } - }), Map.entry(Map.class, (o, v) -> { - if (v instanceof LinkedHashMap) { - o.writeByte((byte) 9); - } else { - o.writeByte((byte) 10); - } - @SuppressWarnings("unchecked") final Map map = (Map) v; - o.writeVInt(map.size()); - for (Map.Entry entry : map.entrySet()) { - o.writeString(entry.getKey()); - o.writeGenericValue(entry.getValue()); - } - }), Map.entry(Byte.class, (o, v) -> { - o.writeByte((byte) 11); - o.writeByte((Byte) v); - }), Map.entry(Date.class, (o, v) -> { - o.writeByte((byte) 12); - o.writeLong(((Date) v).getTime()); - }), Map.entry(ReadableInstant.class, (o, v) -> { - o.writeByte((byte) 13); - final ReadableInstant instant = (ReadableInstant) v; - o.writeString(instant.getZone().getID()); - o.writeLong(instant.getMillis()); - }), Map.entry(BytesReference.class, (o, v) -> { - o.writeByte((byte) 14); - o.writeBytesReference((BytesReference) v); - }), Map.entry(Text.class, (o, v) -> { - o.writeByte((byte) 15); - o.writeText((Text) v); - }), Map.entry(Short.class, (o, v) -> { - o.writeByte((byte) 16); - o.writeShort((Short) v); - }), Map.entry(int[].class, (o, v) -> { - o.writeByte((byte) 17); - o.writeIntArray((int[]) v); - }), Map.entry(long[].class, (o, v) -> { - o.writeByte((byte) 18); - o.writeLongArray((long[]) v); - }), Map.entry(float[].class, (o, v) -> { - o.writeByte((byte) 19); - o.writeFloatArray((float[]) v); - }), Map.entry(double[].class, (o, v) -> { - o.writeByte((byte) 20); - o.writeDoubleArray((double[]) v); - }), Map.entry(BytesRef.class, (o, v) -> { - o.writeByte((byte) 21); - o.writeBytesRef((BytesRef) v); - }), Map.entry(GeoPoint.class, (o, v) -> { - o.writeByte((byte) 22); - o.writeGeoPoint((GeoPoint) v); - }), Map.entry(ZonedDateTime.class, (o, v) -> { - o.writeByte((byte) 23); - final ZonedDateTime zonedDateTime = (ZonedDateTime) v; - o.writeString(zonedDateTime.getZone().getId()); - o.writeLong(zonedDateTime.toInstant().toEpochMilli()); - }), Map.entry(JodaCompatibleZonedDateTime.class, (o, v) -> { - // write the joda compatibility datetime as joda datetime - o.writeByte((byte) 13); - final JodaCompatibleZonedDateTime zonedDateTime = (JodaCompatibleZonedDateTime) v; - String zoneId = zonedDateTime.getZonedDateTime().getZone().getId(); - // joda does not understand "Z" for utc, so we must special case - o.writeString(zoneId.equals("Z") ? DateTimeZone.UTC.getID() : zoneId); - o.writeLong(zonedDateTime.toInstant().toEpochMilli()); - })); - } + private static final Map, Writer> WRITERS = Map.ofEntries( + entry( + String.class, + (o, v) -> { + o.writeByte((byte) 0); + o.writeString((String) v); + }), + entry( + Integer.class, + (o, v) -> { + o.writeByte((byte) 1); + o.writeInt((Integer) v); + }), + entry( + Long.class, + (o, v) -> { + o.writeByte((byte) 2); + o.writeLong((Long) v); + }), + entry( + Float.class, + (o, v) -> { + o.writeByte((byte) 3); + o.writeFloat((float) v); + }), + entry(Double.class, + (o, v) -> { + o.writeByte((byte) 4); + o.writeDouble((double) v); + }), + entry( + Boolean.class, + (o, v) -> { + o.writeByte((byte) 5); + o.writeBoolean((boolean) v); + }), + entry( + byte[].class, + (o, v) -> { + o.writeByte((byte) 6); + final byte[] bytes = (byte[]) v; + o.writeVInt(bytes.length); + o.writeBytes(bytes); + }), + entry( + List.class, + (o, v) -> { + o.writeByte((byte) 7); + final List list = (List) v; + o.writeVInt(list.size()); + for (Object item : list) { + o.writeGenericValue(item); + } + }), + entry( + Object[].class, + (o, v) -> { + o.writeByte((byte) 8); + final Object[] list = (Object[]) v; + o.writeVInt(list.length); + for (Object item : list) { + o.writeGenericValue(item); + } + }), + entry( + Map.class, + (o, v) -> { + if (v instanceof LinkedHashMap) { + o.writeByte((byte) 9); + } else { + o.writeByte((byte) 10); + } + @SuppressWarnings("unchecked") final Map map = (Map) v; + o.writeVInt(map.size()); + for (Map.Entry entry : map.entrySet()) { + o.writeString(entry.getKey()); + o.writeGenericValue(entry.getValue()); + } + }), + entry( + Byte.class, + (o, v) -> { + o.writeByte((byte) 11); + o.writeByte((Byte) v); + }), + entry( + Date.class, + (o, v) -> { + o.writeByte((byte) 12); + o.writeLong(((Date) v).getTime()); + }), + entry( + ReadableInstant.class, + (o, v) -> { + o.writeByte((byte) 13); + final ReadableInstant instant = (ReadableInstant) v; + o.writeString(instant.getZone().getID()); + o.writeLong(instant.getMillis()); + }), + entry( + BytesReference.class, + (o, v) -> { + o.writeByte((byte) 14); + o.writeBytesReference((BytesReference) v); + }), + entry( + Text.class, + (o, v) -> { + o.writeByte((byte) 15); + o.writeText((Text) v); + }), + entry( + Short.class, + (o, v) -> { + o.writeByte((byte) 16); + o.writeShort((Short) v); + }), + entry( + int[].class, + (o, v) -> { + o.writeByte((byte) 17); + o.writeIntArray((int[]) v); + }), + entry( + long[].class, + (o, v) -> { + o.writeByte((byte) 18); + o.writeLongArray((long[]) v); + }), + entry( + float[].class, + (o, v) -> { + o.writeByte((byte) 19); + o.writeFloatArray((float[]) v); + }), + entry( + double[].class, + (o, v) -> { + o.writeByte((byte) 20); + o.writeDoubleArray((double[]) v); + }), + entry( + BytesRef.class, + (o, v) -> { + o.writeByte((byte) 21); + o.writeBytesRef((BytesRef) v); + }), + entry( + GeoPoint.class, + (o, v) -> { + o.writeByte((byte) 22); + o.writeGeoPoint((GeoPoint) v); + }), + entry( + ZonedDateTime.class, + (o, v) -> { + o.writeByte((byte) 23); + final ZonedDateTime zonedDateTime = (ZonedDateTime) v; + o.writeString(zonedDateTime.getZone().getId()); + o.writeLong(zonedDateTime.toInstant().toEpochMilli()); + }), + entry( + JodaCompatibleZonedDateTime.class, + (o, v) -> { + // write the joda compatibility datetime as joda datetime + o.writeByte((byte) 13); + final JodaCompatibleZonedDateTime zonedDateTime = (JodaCompatibleZonedDateTime) v; + String zoneId = zonedDateTime.getZonedDateTime().getZone().getId(); + // joda does not understand "Z" for utc, so we must special case + o.writeString(zoneId.equals("Z") ? DateTimeZone.UTC.getID() : zoneId); + o.writeLong(zonedDateTime.toInstant().toEpochMilli()); + })); /** * Notice: when serialization a map, the stream out map with the stream in map maybe have the diff --git a/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java b/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java index 14e5e660e1f67..a903593c85e67 100644 --- a/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java +++ b/server/src/main/java/org/elasticsearch/search/lookup/LeafSearchLookup.java @@ -39,7 +39,11 @@ public LeafSearchLookup(LeafReaderContext ctx, LeafDocLookup docMap, SourceLooku this.docMap = docMap; this.sourceLookup = sourceLookup; this.fieldsLookup = fieldsLookup; - this.asMap = Map.of("doc", docMap, "_doc", docMap, "_source", sourceLookup, "_fields", fieldsLookup); + this.asMap = Map.of( + "doc", docMap, + "_doc", docMap, + "_source", sourceLookup, + "_fields", fieldsLookup); } public Map asMap() { diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java index ca0db0feb90f6..580ea76429388 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportResizeActionTests.java @@ -43,6 +43,7 @@ import org.elasticsearch.test.gateway.TestGatewayAllocator; import java.util.Collections; +import java.util.Set; import static java.util.Collections.emptyMap; import static org.hamcrest.Matchers.equalTo; @@ -214,7 +215,12 @@ public void testShrinkIndexSettings() { } private DiscoveryNode newNode(String nodeId) { - return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), - java.util.Set.of(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA), Version.CURRENT); + return new DiscoveryNode( + nodeId, + buildNewFakeTransportAddress(), + emptyMap(), + Set.of(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA), + Version.CURRENT); } + } diff --git a/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java b/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java index 9b9ae787545c1..59c11b2bc9442 100644 --- a/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/structure/RoutingIteratorTests.java @@ -43,12 +43,10 @@ import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static java.util.Collections.singletonMap; -import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; @@ -250,11 +248,8 @@ public void testAttributePreferenceRouting() { ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING .getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable).build(); - Map node1Attributes = new HashMap<>(); - node1Attributes.put("rack_id", "rack_1"); - node1Attributes.put("zone", "zone1"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() - .add(newNode("node1", unmodifiableMap(node1Attributes))) + .add(newNode("node1", Map.of("rack_id", "rack_1", "zone", "zone1"))) .add(newNode("node2", Map.of("rack_id", "rack_2", "zone", "zone2"))) .localNodeId("node1") ).build(); diff --git a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index cbafeb92f6765..3a78b4786fc5c 100644 --- a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -2705,16 +2705,16 @@ public ClusterState execute(ClusterState currentState) { shards.put(new ShardId(idxName, "_na_", 1), new ShardSnapshotStatus("unknown-node", State.ABORTED, "aborted")); shards.put(new ShardId(idxName, "_na_", 2), new ShardSnapshotStatus("unknown-node", State.ABORTED, "aborted")); return ClusterState.builder(currentState) - .putCustom(SnapshotsInProgress.TYPE, new SnapshotsInProgress(List.of(new Entry(new Snapshot(repositoryName, - createSnapshotResponse.getSnapshotInfo().snapshotId()), - true, - false, - State.ABORTED, - Collections.singletonList(indexId), - System.currentTimeMillis(), - repositoryData.getGenId(), - shards.build())))) - .build(); + .putCustom(SnapshotsInProgress.TYPE, new SnapshotsInProgress(List.of(new Entry( + new Snapshot(repositoryName, createSnapshotResponse.getSnapshotInfo().snapshotId()), + true, + false, + State.ABORTED, + Collections.singletonList(indexId), + System.currentTimeMillis(), + repositoryData.getGenId(), + shards.build())))) + .build(); } @Override diff --git a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java index d80959b01ef3c..0ee86a6058c63 100644 --- a/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java +++ b/x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTask.java @@ -39,9 +39,7 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -193,9 +191,6 @@ synchronized void coordinateReads() { numOutstandingReads++; sendShardChangesRequest(from, requestOpCount, maxRequiredSeqNo); lastRequestedSeqNo = maxRequiredSeqNo; - Map s = new HashMap<>(); - s.put("a","b"); - Collections.unmodifiableMap(s); } if (numOutstandingReads == 0 && hasReadBudget()) { From a4daa447c39b2bee4d85b4a655e2929e37445f0e Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Sun, 21 Apr 2019 21:44:05 -0400 Subject: [PATCH 03/20] Fix copy that breaks things --- .../index/mapper/DocumentMapperParser.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java index f3ba3e13692f1..b1bf7a10fffe1 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java @@ -33,6 +33,7 @@ import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.indices.mapper.MapperRegistry; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -126,9 +127,18 @@ private DocumentMapper parse(String type, Map mapping, String de Map meta = (Map) mapping.remove("_meta"); if (meta != null) { - // It may not be required to copy meta here to maintain immutability - // but the cost is pretty low here. - docBuilder.meta(Map.copyOf(meta)); + /* + * It may not be required to copy meta here to maintain immutability but the cost is pretty low here. + * + * Note: this copy can not be replaced by Map#copyOf because we rely on consistent serialization order since we do byte-level + * checks on the mapping between what we receive from the master and what we have locally. As Map#copyOf is not necessarily + * the same underlying map implementation, we could end up with a different iteration order. + * + * Do not change this to Map#copyOf or any other method of copying meta that could change the iteration order. + */ + // TODO: this should almost surely be a copy as a LinkedHashMap to have the ordering guarantees that we are relying on. + // TODO: investigate the above note about whether or not we really need to be copying here, the ideal outcome would be to not + docBuilder.meta(Collections.unmodifiableMap(new HashMap<>(meta))); } checkNoRemainingFields(mapping, parserContext.indexVersionCreated(), "Root mapping definition has unsupported parameters: "); From 114c749f7da8dcec82626e9f487ee1b99c020bc6 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Sun, 21 Apr 2019 21:47:06 -0400 Subject: [PATCH 04/20] Combine comments --- .../elasticsearch/index/mapper/DocumentMapperParser.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java index b1bf7a10fffe1..d9ba41cefafc6 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java @@ -135,9 +135,11 @@ private DocumentMapper parse(String type, Map mapping, String de * the same underlying map implementation, we could end up with a different iteration order. * * Do not change this to Map#copyOf or any other method of copying meta that could change the iteration order. + * + * TODO: + * - this should almost surely be a copy as a LinkedHashMap to have the ordering guarantees that we are relying on + * - investigate the above note about whether or not we really need to be copying here, the ideal outcome would be to not */ - // TODO: this should almost surely be a copy as a LinkedHashMap to have the ordering guarantees that we are relying on. - // TODO: investigate the above note about whether or not we really need to be copying here, the ideal outcome would be to not docBuilder.meta(Collections.unmodifiableMap(new HashMap<>(meta))); } From 9e5527ac2e34166ad71bbb6a423b95c2a35bc223 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 07:57:15 -0400 Subject: [PATCH 05/20] Further comment iteration --- .../org/elasticsearch/index/mapper/DocumentMapperParser.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java index d9ba41cefafc6..8028960ab4262 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java @@ -132,7 +132,8 @@ private DocumentMapper parse(String type, Map mapping, String de * * Note: this copy can not be replaced by Map#copyOf because we rely on consistent serialization order since we do byte-level * checks on the mapping between what we receive from the master and what we have locally. As Map#copyOf is not necessarily - * the same underlying map implementation, we could end up with a different iteration order. + * the same underlying map implementation, we could end up with a different iteration order. For reference, see + * MapperService#assertSerializtion and GitHub issues #10302 and #10318. * * Do not change this to Map#copyOf or any other method of copying meta that could change the iteration order. * From afca1efeed06458430e194df7743a8169fdec365 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 08:29:56 -0400 Subject: [PATCH 06/20] Fix bogus test --- .../mustache/CustomMustacheFactory.java | 5 ++-- .../mustache/CustomMustacheFactoryTests.java | 24 ++++++++++++------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java index a398491121edd..69f3d5af2795c 100644 --- a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java +++ b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java @@ -30,6 +30,7 @@ import com.github.mustachejava.codes.DefaultMustache; import com.github.mustachejava.codes.IterableCode; import com.github.mustachejava.codes.WriteCode; +import org.apache.lucene.search.highlight.DefaultEncoder; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; @@ -86,11 +87,11 @@ public void encode(String value, Writer writer) { } static Encoder createEncoder(String mimeType) { - Supplier supplier = ENCODERS.get(mimeType); + final Supplier supplier = ENCODERS.get(mimeType); if (supplier == null) { throw new IllegalArgumentException("No encoder found for MIME type [" + mimeType + "]"); } - return supplier.get(); + return ENCODERS.get(mimeType).get(); } @Override diff --git a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/CustomMustacheFactoryTests.java b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/CustomMustacheFactoryTests.java index 28c536d788e6a..f5465f256c225 100644 --- a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/CustomMustacheFactoryTests.java +++ b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/CustomMustacheFactoryTests.java @@ -37,14 +37,22 @@ public class CustomMustacheFactoryTests extends ESTestCase { public void testCreateEncoder() { - IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder(null)); - assertThat(e.getMessage(), equalTo("No encoder found for MIME type [null]")); - - e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder("")); - assertThat(e.getMessage(), equalTo("No encoder found for MIME type []")); - - e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder("test")); - assertThat(e.getMessage(), equalTo("No encoder found for MIME type [test]")); + { + final IllegalArgumentException e = + expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder("non-existent")); + assertThat(e.getMessage(), equalTo("No encoder found for MIME type [non-existent]")); + } + + { + final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder("")); + assertThat(e.getMessage(), equalTo("No encoder found for MIME type []")); + } + + { + final IllegalArgumentException e = + expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder("test")); + assertThat(e.getMessage(), equalTo("No encoder found for MIME type [test]")); + } assertThat(CustomMustacheFactory.createEncoder(CustomMustacheFactory.JSON_MIME_TYPE_WITH_CHARSET), instanceOf(CustomMustacheFactory.JsonEscapeEncoder.class)); From 95ce478879d2f92b591702827f400908d618f2c6 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 08:55:06 -0400 Subject: [PATCH 07/20] Fix ML NPE --- .../xpack/ml/utils/TypedChainTaskExecutor.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java index 1b07d6cff8352..294ed73712ec8 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/utils/TypedChainTaskExecutor.java @@ -63,7 +63,8 @@ private synchronized void execute(T previousValue, ActionListener> liste collectedResponses.add(previousValue); if (continuationPredicate.test(previousValue)) { if (tasks.isEmpty()) { - listener.onResponse(List.copyOf(collectedResponses)); + // noinspection Java9CollectionFactory (because the list can contain null entries) + listener.onResponse(Collections.unmodifiableList(new ArrayList<>(collectedResponses))); return; } ChainTask task = tasks.pop(); @@ -83,7 +84,8 @@ protected void doRun() { } }); } else { - listener.onResponse(List.copyOf(collectedResponses)); + // noinspection Java9CollectionFactory (because the list can contain null entries) + listener.onResponse(Collections.unmodifiableList(new ArrayList<>(collectedResponses))); } } From 251e57b142e00b3036109e29253921a7c418464a Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 08:58:54 -0400 Subject: [PATCH 08/20] Revert inadvertent change --- .../elasticsearch/script/mustache/CustomMustacheFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java index 69f3d5af2795c..9750f3918f0d6 100644 --- a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java +++ b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java @@ -91,7 +91,7 @@ static Encoder createEncoder(String mimeType) { if (supplier == null) { throw new IllegalArgumentException("No encoder found for MIME type [" + mimeType + "]"); } - return ENCODERS.get(mimeType).get(); + return supplier.get(); } @Override From 4f2de47fbd843e0011f053ac8d7be99d9edf6dc1 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 12:06:04 -0400 Subject: [PATCH 09/20] Fix type --- .../privileges/AbstractIndicesPrivileges.java | 13 +++++++------ .../user/privileges/IndicesPrivileges.java | 15 ++++++++------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java index 8c16e530c524c..519871194b045 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java @@ -31,6 +31,7 @@ import java.io.UncheckedIOException; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Objects; import java.util.Set; @@ -43,8 +44,8 @@ public abstract class AbstractIndicesPrivileges { static final ParseField FIELD_PERMISSIONS = new ParseField("field_security"); static final ParseField QUERY = new ParseField("query"); - protected final Set indices; - protected final Set privileges; + protected final List indices; + protected final List privileges; protected final boolean allowRestrictedIndices; AbstractIndicesPrivileges(Collection indices, Collection privileges, boolean allowRestrictedIndices) { @@ -54,15 +55,15 @@ public abstract class AbstractIndicesPrivileges { if (null == privileges || privileges.isEmpty()) { throw new IllegalArgumentException("indices privileges must define at least one privilege"); } - this.indices = Set.copyOf(indices); - this.privileges = Set.copyOf(privileges); + this.indices = List.copyOf(indices); + this.privileges = List.copyOf(privileges); this.allowRestrictedIndices = allowRestrictedIndices; } /** * The indices names covered by the privileges. */ - public Set getIndices() { + public List getIndices() { return this.indices; } @@ -71,7 +72,7 @@ public Set getIndices() { * such privileges, but the {@code String} datatype allows for flexibility in defining * finer grained privileges. */ - public Set getPrivileges() { + public List getPrivileges() { return this.privileges; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java index 26c303304cd66..6e4fff0708ddd 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.Objects; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; @@ -48,8 +49,8 @@ public final class IndicesPrivileges extends AbstractIndicesPrivileges implement static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("indices_privileges", false, constructorObjects -> { int i = 0; - final Collection indices = (Collection) constructorObjects[i++]; - final Collection privileges = (Collection) constructorObjects[i++]; + final List indices = (List) constructorObjects[i++]; + final List privileges = (List) constructorObjects[i++]; final boolean allowRestrictedIndices = (Boolean) constructorObjects[i++]; final FieldSecurity fields = (FieldSecurity) constructorObjects[i++]; final String query = (String) constructorObjects[i]; @@ -68,7 +69,7 @@ public final class IndicesPrivileges extends AbstractIndicesPrivileges implement // missing query means all documents, i.e. no restrictions private final @Nullable String query; - private IndicesPrivileges(Collection indices, Collection privileges, boolean allowRestrictedIndices, + private IndicesPrivileges(List indices, List privileges, boolean allowRestrictedIndices, @Nullable FieldSecurity fieldSecurity, @Nullable String query) { super(indices, privileges, allowRestrictedIndices); this.fieldSecurity = fieldSecurity; @@ -165,9 +166,9 @@ public static Builder builder() { public static final class Builder { private @Nullable - Collection indices = null; + List indices = null; private @Nullable - Collection privileges = null; + List privileges = null; private @Nullable Collection grantedFields = null; private @Nullable @@ -183,7 +184,7 @@ public Builder indices(String... indices) { return indices(Arrays.asList(Objects.requireNonNull(indices, "indices required"))); } - public Builder indices(Collection indices) { + public Builder indices(List indices) { this.indices = Objects.requireNonNull(indices, "indices required"); return this; } @@ -192,7 +193,7 @@ public Builder privileges(String... privileges) { return privileges(Arrays.asList(Objects.requireNonNull(privileges, "privileges required"))); } - public Builder privileges(Collection privileges) { + public Builder privileges(List privileges) { this.privileges = Objects.requireNonNull(privileges, "privileges required"); return this; } From 3d881de5cff4eae85ebbe271db50647f97f45e10 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 13:30:36 -0400 Subject: [PATCH 10/20] Fix LoggingAuditTrail tests --- .../audit/logfile/LoggingAuditTrailTests.java | 77 ++++++++++--------- 1 file changed, 42 insertions(+), 35 deletions(-) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java index 55d5bd579c12d..0aaf9db7f90d3 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java @@ -36,11 +36,11 @@ import org.elasticsearch.xpack.core.security.authc.Authentication; import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef; import org.elasticsearch.xpack.core.security.authc.AuthenticationToken; +import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.AuthorizationInfo; import org.elasticsearch.xpack.core.security.user.SystemUser; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.security.audit.AuditTrail; import org.elasticsearch.xpack.security.audit.AuditUtil; -import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.AuthorizationInfo; import org.elasticsearch.xpack.security.rest.RemoteHostHeader; import org.elasticsearch.xpack.security.transport.filter.IPFilter; import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule; @@ -66,10 +66,10 @@ import java.util.regex.Pattern; import static org.elasticsearch.xpack.security.audit.logfile.LoggingAuditTrail.PRINCIPAL_ROLES_FIELD_NAME; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -178,6 +178,7 @@ public void init() throws Exception { .put("xpack.security.audit.logfile.events.emit_request_body", includeRequestBody) .build(); localNode = mock(DiscoveryNode.class); + when(localNode.getId()).thenReturn(randomAlphaOfLength(16)); when(localNode.getAddress()).thenReturn(buildNewFakeTransportAddress()); clusterService = mock(ClusterService.class); when(clusterService.localNode()).thenReturn(localNode); @@ -249,11 +250,11 @@ public void testAnonymousAccessDeniedRest() throws Exception { .put(LoggingAuditTrail.ORIGIN_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.ORIGIN_ADDRESS_FIELD_NAME, NetworkAddress.format(address)) .put(LoggingAuditTrail.REQUEST_METHOD_FIELD_NAME, request.method().toString()) - .put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, - includeRequestBody && Strings.hasLength(expectedMessage) ? expectedMessage : null) .put(LoggingAuditTrail.REQUEST_ID_FIELD_NAME, requestId) - .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri") - .put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, null); + .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri"); + if (includeRequestBody && Strings.hasLength(expectedMessage)) { + checkedFields.put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, expectedMessage); + } opaqueId(threadContext, checkedFields); forwardedFor(threadContext, checkedFields); assertMsg(logger, checkedFields.immutableMap()); @@ -346,16 +347,18 @@ public void testAuthenticationFailedRest() throws Exception { final MapBuilder checkedFields = new MapBuilder<>(commonFields); checkedFields.put(LoggingAuditTrail.EVENT_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.EVENT_ACTION_FIELD_NAME, "authentication_failed") - .put(LoggingAuditTrail.ACTION_FIELD_NAME, null) .put(LoggingAuditTrail.PRINCIPAL_FIELD_NAME, mockToken.principal()) .put(LoggingAuditTrail.ORIGIN_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.ORIGIN_ADDRESS_FIELD_NAME, NetworkAddress.format(address)) .put(LoggingAuditTrail.REQUEST_METHOD_FIELD_NAME, request.method().toString()) - .put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, - includeRequestBody && Strings.hasLength(expectedMessage) ? expectedMessage : null) .put(LoggingAuditTrail.REQUEST_ID_FIELD_NAME, requestId) - .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri") - .put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, params.isEmpty() ? null : "foo=bar"); + .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri"); + if (includeRequestBody && Strings.hasLength(expectedMessage)) { + checkedFields.put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, expectedMessage); + } + if (params.isEmpty() == false) { + checkedFields.put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, "foo=bar"); + } opaqueId(threadContext, checkedFields); forwardedFor(threadContext, checkedFields); assertMsg(logger, checkedFields.immutableMap()); @@ -387,16 +390,17 @@ public void testAuthenticationFailedRestNoToken() throws Exception { final MapBuilder checkedFields = new MapBuilder<>(commonFields); checkedFields.put(LoggingAuditTrail.EVENT_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.EVENT_ACTION_FIELD_NAME, "authentication_failed") - .put(LoggingAuditTrail.ACTION_FIELD_NAME, null) - .put(LoggingAuditTrail.PRINCIPAL_FIELD_NAME, null) .put(LoggingAuditTrail.ORIGIN_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.ORIGIN_ADDRESS_FIELD_NAME, NetworkAddress.format(address)) .put(LoggingAuditTrail.REQUEST_METHOD_FIELD_NAME, request.method().toString()) - .put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, - includeRequestBody && Strings.hasLength(expectedMessage) ? expectedMessage : null) .put(LoggingAuditTrail.REQUEST_ID_FIELD_NAME, requestId) - .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri") - .put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, params.isEmpty() ? null : "bar=baz"); + .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri"); + if (includeRequestBody && Strings.hasLength(expectedMessage)) { + checkedFields.put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, expectedMessage); + } + if (params.isEmpty() == false) { + checkedFields.put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, "bar=baz"); + } opaqueId(threadContext, checkedFields); forwardedFor(threadContext, checkedFields); assertMsg(logger, checkedFields.immutableMap()); @@ -473,13 +477,15 @@ public void testAuthenticationFailedRealmRest() throws Exception { .put(LoggingAuditTrail.ORIGIN_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.ORIGIN_ADDRESS_FIELD_NAME, NetworkAddress.format(address)) .put(LoggingAuditTrail.PRINCIPAL_FIELD_NAME, mockToken.principal()) - .put(LoggingAuditTrail.ACTION_FIELD_NAME, null) .put(LoggingAuditTrail.REQUEST_METHOD_FIELD_NAME, request.method().toString()) - .put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, - includeRequestBody && Strings.hasLength(expectedMessage) ? expectedMessage : null) .put(LoggingAuditTrail.REQUEST_ID_FIELD_NAME, requestId) - .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri") - .put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, params.isEmpty() ? null : "_param=baz"); + .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri"); + if (includeRequestBody && Strings.hasLength(expectedMessage)) { + checkedFields.put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, expectedMessage); + } + if (params.isEmpty() == false) { + checkedFields.put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, "_param=baz"); + } opaqueId(threadContext, checkedFields); forwardedFor(threadContext, checkedFields); assertMsg(logger, checkedFields.immutableMap()); @@ -639,11 +645,14 @@ public void testTamperedRequestRest() throws Exception { .put(LoggingAuditTrail.ORIGIN_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.ORIGIN_ADDRESS_FIELD_NAME, NetworkAddress.format(address)) .put(LoggingAuditTrail.REQUEST_METHOD_FIELD_NAME, request.method().toString()) - .put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, - includeRequestBody && Strings.hasLength(expectedMessage) ? expectedMessage : null) .put(LoggingAuditTrail.REQUEST_ID_FIELD_NAME, requestId) - .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri") - .put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, params.isEmpty() ? null : "_param=baz"); + .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri"); + if (includeRequestBody && Strings.hasLength(expectedMessage)) { + checkedFields.put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, expectedMessage); + } + if (params.isEmpty() == false) { + checkedFields.put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, "_param=baz"); + } opaqueId(threadContext, checkedFields); forwardedFor(threadContext, checkedFields); assertMsg(logger, checkedFields.immutableMap()); @@ -906,11 +915,14 @@ public void testAuthenticationSuccessRest() throws Exception { .put(LoggingAuditTrail.ORIGIN_TYPE_FIELD_NAME, LoggingAuditTrail.REST_ORIGIN_FIELD_VALUE) .put(LoggingAuditTrail.ORIGIN_ADDRESS_FIELD_NAME, NetworkAddress.format(address)) .put(LoggingAuditTrail.REQUEST_METHOD_FIELD_NAME, request.method().toString()) - .put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, - includeRequestBody && Strings.hasLength(expectedMessage) ? expectedMessage : null) .put(LoggingAuditTrail.REQUEST_ID_FIELD_NAME, requestId) - .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri") - .put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, params.isEmpty() ? null : "foo=bar&evac=true"); + .put(LoggingAuditTrail.URL_PATH_FIELD_NAME, "_uri"); + if (includeRequestBody && Strings.hasLength(expectedMessage)) { + checkedFields.put(LoggingAuditTrail.REQUEST_BODY_FIELD_NAME, expectedMessage); + } + if (params.isEmpty() == false) { + checkedFields.put(LoggingAuditTrail.URL_QUERY_FIELD_NAME, "foo=bar&evac=true"); + } if (user.isRunAs()) { checkedFields.put(LoggingAuditTrail.PRINCIPAL_FIELD_NAME, "running as"); checkedFields.put(LoggingAuditTrail.PRINCIPAL_RUN_BY_FIELD_NAME, "_username"); @@ -1216,8 +1228,6 @@ private static void opaqueId(ThreadContext threadContext, MapBuilder Date: Mon, 22 Apr 2019 18:33:17 -0400 Subject: [PATCH 11/20] Fix tests --- .../client/security/GetUsersResponse.java | 10 ++++----- .../client/security/user/User.java | 13 +++++------ .../user/privileges/ApplicationPrivilege.java | 17 +++++++------- .../ApplicationResourcePrivileges.java | 21 +++++++++--------- .../SecurityRequestConvertersTests.java | 4 ++-- .../SecurityDocumentationIT.java | 7 +++--- .../security/AuthenticateResponseTests.java | 7 +++--- .../security/HasPrivilegesRequestTests.java | 13 ++++++----- .../security/PutPrivilegesRequestTests.java | 22 +++++++++---------- .../ApplicationResourcePrivilegesTests.java | 6 ++--- .../authc/support/UserRoleMapper.java | 8 +++++-- 11 files changed, 66 insertions(+), 62 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java index abb37f28306f0..775fbed3c3549 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java @@ -27,9 +27,9 @@ import org.elasticsearch.common.xcontent.XContentParserUtils; import java.io.IOException; -import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -99,7 +99,7 @@ public int hashCode() { (constructorObjects) -> { int i = 0; final String username = (String) constructorObjects[i++]; - final Collection roles = (Collection) constructorObjects[i++]; + final List roles = (List) constructorObjects[i++]; final Map metadata = (Map) constructorObjects[i++]; final Boolean enabled = (Boolean) constructorObjects[i++]; final String fullName = (String) constructorObjects[i++]; @@ -120,11 +120,11 @@ protected static final class ParsedUser { protected User user; protected boolean enabled; - public ParsedUser(String username, Collection roles, Map metadata, Boolean enabled, + public ParsedUser(String username, List roles, Map metadata, Boolean enabled, @Nullable String fullName, @Nullable String email) { String checkedUsername = Objects.requireNonNull(username, "`username` is required, cannot be null"); - Collection checkedRoles = - Set.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); + List checkedRoles = + List.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); Map checkedMetadata = Collections.unmodifiableMap( Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); this.user = new User(checkedUsername, checkedRoles, checkedMetadata, fullName, email); diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java index 7353b7f350cbf..82ecabc03b6d4 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java @@ -22,11 +22,10 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; -import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; /** * A user to be utilized with security APIs. @@ -35,7 +34,7 @@ public final class User { private final String username; - private final Set roles; + private final List roles; private final Map metadata; @Nullable private final String fullName; @Nullable private final String email; @@ -49,10 +48,10 @@ public final class User { * @param fullName the full name of the user that may be used for display purposes * @param email the email address of the user */ - public User(String username, Collection roles, Map metadata, @Nullable String fullName, + public User(String username, List roles, Map metadata, @Nullable String fullName, @Nullable String email) { this.username = Objects.requireNonNull(username, "`username` is required, cannot be null"); - this.roles = Set.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); + this.roles = List.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); this.metadata = Collections.unmodifiableMap( Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); this.fullName = fullName; @@ -65,7 +64,7 @@ public User(String username, Collection roles, Map metad * @param username the username, also known as the principal, unique for in the scope of a realm * @param roles the roles that this user is assigned */ - public User(String username, Collection roles) { + public User(String username, List roles) { this(username, roles, Collections.emptyMap(), null, null); } @@ -82,7 +81,7 @@ public String getUsername() { * identified by their unique names and each represents as * set of permissions. Can never be {@code null}. */ - public Set getRoles() { + public List getRoles() { return this.roles; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java index 6b8da58f13223..ec78cca6b5c55 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationPrivilege.java @@ -30,11 +30,10 @@ import java.io.IOException; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; @@ -53,10 +52,10 @@ public final class ApplicationPrivilege implements ToXContentObject { private final String application; private final String name; - private final Set actions; + private final List actions; private final Map metadata; - public ApplicationPrivilege(String application, String name, Collection actions, @Nullable Map metadata) { + public ApplicationPrivilege(String application, String name, List actions, @Nullable Map metadata) { if (Strings.isNullOrEmpty(application)) { throw new IllegalArgumentException("application name must be provided"); } else { @@ -70,7 +69,7 @@ public ApplicationPrivilege(String application, String name, Collection if (actions == null || actions.isEmpty()) { throw new IllegalArgumentException("actions must be provided"); } else { - this.actions = Set.copyOf(actions); + this.actions = List.copyOf(actions); } if (metadata == null || metadata.isEmpty()) { this.metadata = Collections.emptyMap(); @@ -87,7 +86,7 @@ public String getName() { return name; } - public Set getActions() { + public List getActions() { return actions; } @@ -98,7 +97,7 @@ public Map getMetadata() { @SuppressWarnings("unchecked") public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( "application_privilege", - true, args -> new ApplicationPrivilege((String) args[0], (String) args[1], (Collection) args[2], + true, args -> new ApplicationPrivilege((String) args[0], (String) args[1], (List) args[2], (Map) args[3])); static { @@ -135,7 +134,7 @@ public static Builder builder() { public static final class Builder { private String applicationName = null; private String privilegeName = null; - private Collection actions = null; + private List actions = null; private Map metadata = null; private Builder() { @@ -156,7 +155,7 @@ public Builder actions(String... actions) { return this; } - public Builder actions(Collection actions) { + public Builder actions(List actions) { this.actions = Objects.requireNonNull(actions); return this; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java index 6dcb049f33e48..a296a80ad49b4 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivileges.java @@ -29,9 +29,8 @@ import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; -import java.util.Collection; +import java.util.List; import java.util.Objects; -import java.util.Set; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; @@ -55,8 +54,8 @@ public final class ApplicationResourcePrivileges implements ToXContentObject { // end up being implicitly set to null in that request. int i = 0; final String application = (String) constructorObjects[i++]; - final Collection privileges = (Collection) constructorObjects[i++]; - final Collection resources = (Collection) constructorObjects[i]; + final List privileges = (List) constructorObjects[i++]; + final List resources = (List) constructorObjects[i]; return new ApplicationResourcePrivileges(application, privileges, resources); }); @@ -67,8 +66,8 @@ public final class ApplicationResourcePrivileges implements ToXContentObject { } private final String application; - private final Set privileges; - private final Set resources; + private final List privileges; + private final List resources; /** * Constructs privileges for resources under an application scope. @@ -83,7 +82,7 @@ public final class ApplicationResourcePrivileges implements ToXContentObject { * The resources names. Cannot be null or empty. Resource identifiers * are completely under the clients control. */ - public ApplicationResourcePrivileges(String application, Collection privileges, Collection resources) { + public ApplicationResourcePrivileges(String application, List privileges, List resources) { if (Strings.isNullOrEmpty(application)) { throw new IllegalArgumentException("application privileges must have an application name"); } @@ -94,19 +93,19 @@ public ApplicationResourcePrivileges(String application, Collection priv throw new IllegalArgumentException("application privileges must refer to at least one resource"); } this.application = application; - this.privileges = Set.copyOf(privileges); - this.resources = Set.copyOf(resources); + this.privileges = List.copyOf(privileges); + this.resources = List.copyOf(resources); } public String getApplication() { return application; } - public Set getResources() { + public List getResources() { return this.resources; } - public Set getPrivileges() { + public List getPrivileges() { return this.privileges; } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/SecurityRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/SecurityRequestConvertersTests.java index 1176cabcc3d9c..99350fc29db8a 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/SecurityRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/SecurityRequestConvertersTests.java @@ -55,7 +55,6 @@ import org.elasticsearch.client.security.user.privileges.Role.IndexPrivilegeName; import org.elasticsearch.common.Strings; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.test.ESTestCase; import java.io.IOException; @@ -353,11 +352,12 @@ public void testPutPrivileges() throws Exception { int noOfApplicationPrivileges = randomIntBetween(2, 4); final List privileges = new ArrayList<>(); for (int count = 0; count < noOfApplicationPrivileges; count++) { + final String[] actions = generateRandomStringArray(3, 5, false, false); privileges.add(ApplicationPrivilege.builder() .application(randomAlphaOfLength(4)) .privilege(randomAlphaOfLengthBetween(3, 5)) - .actions(Sets.newHashSet(generateRandomStringArray(3, 5, false, false))) .metadata(Collections.singletonMap("k1", "v1")) + .actions(actions == null ? Collections.emptyList() : List.of(actions)) .build()); } final RefreshPolicy refreshPolicy = randomFrom(RefreshPolicy.values()); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java index b095ca5a9a0db..9c6b04821a164 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java @@ -97,6 +97,7 @@ import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; + import java.io.IOException; import java.time.Instant; import java.util.ArrayList; @@ -1635,13 +1636,13 @@ public void testPutPrivileges() throws Exception { privileges.add(ApplicationPrivilege.builder() .application("app01") .privilege("all") - .actions(Sets.newHashSet("action:login")) + .actions(List.of("action:login")) .metadata(Collections.singletonMap("k1", "v1")) .build()); privileges.add(ApplicationPrivilege.builder() .application("app01") .privilege("write") - .actions(Sets.newHashSet("action:write")) + .actions(List.of("action:write")) .build()); final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, RefreshPolicy.IMMEDIATE); // end::put-privileges-request @@ -1664,7 +1665,7 @@ public void testPutPrivileges() throws Exception { privileges.add(ApplicationPrivilege.builder() .application("app01") .privilege("all") - .actions(Sets.newHashSet("action:login")) + .actions(List.of("action:login")) .metadata(Collections.singletonMap("k1", "v1")) .build()); final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, RefreshPolicy.IMMEDIATE); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/AuthenticateResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/AuthenticateResponseTests.java index e348cb4d46c7e..7ca84283c501c 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/AuthenticateResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/AuthenticateResponseTests.java @@ -27,7 +27,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -49,8 +48,8 @@ public void testFromXContent() throws IOException { } public void testEqualsAndHashCode() { - final AuthenticateResponse reponse = createTestInstance(); - EqualsHashCodeTestUtils.checkEqualsAndHashCode(reponse, this::copy, + final AuthenticateResponse response = createTestInstance(); + EqualsHashCodeTestUtils.checkEqualsAndHashCode(response, this::copy, this::mutate); } @@ -123,7 +122,7 @@ private AuthenticateResponse mutate(AuthenticateResponse response) { originalUser.getMetadata(), originalUser.getFullName(), originalUser.getEmail()), response.enabled(), response.getAuthenticationRealm(), response.getLookupRealm()); case 2: - final Collection wrongRoles = new ArrayList<>(originalUser.getRoles()); + final List wrongRoles = new ArrayList<>(originalUser.getRoles()); wrongRoles.add(randomAlphaOfLengthBetween(1, 4)); return new AuthenticateResponse(new User(originalUser.getUsername(), wrongRoles, originalUser.getMetadata(), originalUser.getFullName(), originalUser.getEmail()), response.enabled(), response.getAuthenticationRealm(), diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/HasPrivilegesRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/HasPrivilegesRequestTests.java index fa1245925d7ea..da8cf92bdc14e 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/HasPrivilegesRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/HasPrivilegesRequestTests.java @@ -31,7 +31,9 @@ import java.io.IOException; import java.util.Arrays; +import java.util.Collections; import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; import java.util.Set; @@ -87,12 +89,13 @@ public void testEqualsAndHashCode() { .privileges(generateRandomStringArray(3, 8, false, false)) .allowRestrictedIndices(randomBoolean()) .build())); + final String[] privileges = generateRandomStringArray(3, 8, false, false); + final String[] resources = generateRandomStringArray(2, 6, false, false); final Set application = Sets.newHashSet(randomArray(1, 5, ApplicationResourcePrivileges[]::new, - () -> new ApplicationResourcePrivileges( - randomAlphaOfLengthBetween(5, 12), - Sets.newHashSet(generateRandomStringArray(3, 8, false, false)), - Sets.newHashSet(generateRandomStringArray(2, 6, false, false)) - ))); + () -> new ApplicationResourcePrivileges( + randomAlphaOfLengthBetween(5, 12), + privileges == null ? Collections.emptyList() : List.of(privileges), + resources == null ? Collections.emptyList() : List.of(resources)))); final HasPrivilegesRequest request = new HasPrivilegesRequest(cluster, indices, application); EqualsHashCodeTestUtils.checkEqualsAndHashCode(request, this::copy, this::mutate); } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/PutPrivilegesRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/PutPrivilegesRequestTests.java index 8c60382eeec38..6c6c9f7ea8709 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/PutPrivilegesRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/PutPrivilegesRequestTests.java @@ -45,7 +45,7 @@ public void testConstructor() { Arrays.asList(Collections.singletonList(ApplicationPrivilege.builder() .application("app01") .privilege("all") - .actions(Sets.newHashSet("action:login", "action:logout")) + .actions(List.of("action:login", "action:logout")) .metadata(Collections.singletonMap("k1", "v1")) .build()), null, Collections.emptyList())); @@ -69,8 +69,8 @@ public void testToXContent() throws IOException { + " \"application\" : \"app01\",\n" + " \"name\" : \"all\",\n" + " \"actions\" : [\n" - + " \"action:logout\",\n" - + " \"action:login\"\n" + + " \"action:login\",\n" + + " \"action:logout\"\n" + " ],\n" + " \"metadata\" : {\n" + " \"k1\" : \"v1\"\n" @@ -88,8 +88,8 @@ public void testToXContent() throws IOException { + " \"application\" : \"app02\",\n" + " \"name\" : \"all\",\n" + " \"actions\" : [\n" - + " \"action:logout\",\n" - + " \"action:login\"\n" + + " \"action:login\",\n" + + " \"action:logout\"\n" + " ],\n" + " \"metadata\" : {\n" + " \"k2\" : \"v2\"\n" @@ -101,18 +101,18 @@ public void testToXContent() throws IOException { privileges.add(ApplicationPrivilege.builder() .application("app01") .privilege("all") - .actions(Sets.newHashSet("action:login", "action:logout")) + .actions(List.of("action:login", "action:logout")) .metadata(Collections.singletonMap("k1", "v1")) .build()); privileges.add(ApplicationPrivilege.builder() .application("app01") .privilege("read") - .actions(Sets.newHashSet("data:read")) + .actions(List.of("data:read")) .build()); privileges.add(ApplicationPrivilege.builder() .application("app02") .privilege("all") - .actions(Sets.newHashSet("action:login", "action:logout")) + .actions(List.of("action:login", "action:logout")) .metadata(Collections.singletonMap("k2", "v2")) .build()); final RefreshPolicy refreshPolicy = randomFrom(RefreshPolicy.values()); @@ -126,13 +126,13 @@ public void testEqualsHashCode() { privileges.add(ApplicationPrivilege.builder() .application(randomAlphaOfLength(5)) .privilege(randomAlphaOfLength(3)) - .actions(Sets.newHashSet(randomAlphaOfLength(5), randomAlphaOfLength(5))) + .actions(List.of(randomAlphaOfLength(5), randomAlphaOfLength(5))) .metadata(Collections.singletonMap(randomAlphaOfLength(3), randomAlphaOfLength(3))) .build()); privileges.add(ApplicationPrivilege.builder() .application(randomAlphaOfLength(5)) .privilege(randomAlphaOfLength(3)) - .actions(Sets.newHashSet(randomAlphaOfLength(5), randomAlphaOfLength(5))) + .actions(List.of(randomAlphaOfLength(5), randomAlphaOfLength(5))) .metadata(Collections.singletonMap(randomAlphaOfLength(3), randomAlphaOfLength(3))) .build()); final RefreshPolicy refreshPolicy = randomFrom(RefreshPolicy.values()); @@ -156,7 +156,7 @@ private static PutPrivilegesRequest mutateTestItem(PutPrivilegesRequest original privileges.add(ApplicationPrivilege.builder() .application(randomAlphaOfLength(5)) .privilege(randomAlphaOfLength(3)) - .actions(Sets.newHashSet(randomAlphaOfLength(6))) + .actions(List.of(randomAlphaOfLength(6))) .build()); return new PutPrivilegesRequest(privileges, original.getRefreshPolicy()); case 1: diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivilegesTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivilegesTests.java index 29845441a2c05..2a0d89500ae89 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivilegesTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/ApplicationResourcePrivilegesTests.java @@ -24,8 +24,8 @@ import java.io.IOException; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; +import java.util.List; import static org.hamcrest.Matchers.is; @@ -62,7 +62,7 @@ public void testEmptyApplicationName() { } public void testEmptyPrivileges() { - final Collection emptyPrivileges = randomBoolean() ? Collections.emptyList() : null; + final List emptyPrivileges = randomBoolean() ? Collections.emptyList() : null; final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new ApplicationResourcePrivileges(randomAlphaOfLengthBetween(1, 8), emptyPrivileges, @@ -71,7 +71,7 @@ public void testEmptyPrivileges() { } public void testEmptyResources() { - final Collection emptyResources = randomBoolean() ? Collections.emptyList() : null; + final List emptyResources = randomBoolean() ? Collections.emptyList() : null; final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new ApplicationResourcePrivileges(randomAlphaOfLengthBetween(1, 8), Arrays.asList(randomArray(1, 8, size -> new String[size], () -> randomAlphaOfLengthBetween(1, 8))), diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java index 107b578cc0161..c23cae1aa878d 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/UserRoleMapper.java @@ -21,6 +21,8 @@ import java.util.Collection; import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -61,10 +63,12 @@ public UserData(String username, @Nullable String dn, Collection groups, Map metadata, RealmConfig realm) { this.username = username; this.dn = dn; + // noinspection Java9CollectionFactory (because null values happen in some tests, is this realistic?) this.groups = groups == null || groups.isEmpty() - ? Collections.emptySet() : Set.copyOf(groups); + ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(groups)); + // noinspection Java9CollectionFactory (because null values happen in production code, can such keys be dropped?) this.metadata = metadata == null || metadata.isEmpty() - ? Collections.emptyMap() : Collections.unmodifiableMap(metadata); + ? Collections.emptyMap() : Collections.unmodifiableMap(new HashMap<>(metadata)); this.realm = realm; } From 69e5f967b2c3799628dc5efa2379d510ca9839dc Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 22:38:22 -0400 Subject: [PATCH 12/20] Fix tests relying on iteration order --- .../privileges/AbstractIndicesPrivileges.java | 16 ++++++++-------- .../user/privileges/IndicesPrivileges.java | 8 ++++---- .../user/privileges/UserIndicesPrivileges.java | 14 +++++++------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java index 519871194b045..3c4a62b7f8529 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java @@ -106,8 +106,8 @@ public static class FieldSecurity implements ToXContentObject { @SuppressWarnings("unchecked") private static FieldSecurity buildObjectFromParserArgs(Object[] args) { return new FieldSecurity( - (Collection) args[0], - (Collection) args[1] + (List) args[0], + (List) args[1] ); } @@ -121,15 +121,15 @@ static FieldSecurity parse(XContentParser parser, Void context) throws IOExcepti } // null or singleton '*' means all fields are granted, empty means no fields are granted - private final Set grantedFields; + private final List grantedFields; // null or empty means no fields are denied - private final Set deniedFields; + private final List deniedFields; FieldSecurity(Collection grantedFields, Collection deniedFields) { // unspecified granted fields means no restriction - this.grantedFields = grantedFields == null ? null : Set.copyOf(grantedFields); + this.grantedFields = grantedFields == null ? null : List.copyOf(grantedFields); // unspecified denied fields means no restriction - this.deniedFields = deniedFields == null ? null : Set.copyOf(deniedFields); + this.deniedFields = deniedFields == null ? null : List.copyOf(deniedFields); } /** @@ -137,7 +137,7 @@ static FieldSecurity parse(XContentParser parser, Void context) throws IOExcepti * all the document's fields are granted access to. Can also be empty, in which * case no fields are granted access to. */ - public Set getGrantedFields() { + public List getGrantedFields() { return grantedFields; } @@ -145,7 +145,7 @@ public Set getGrantedFields() { * The document fields that cannot be accessed or queried. Can be null or empty, * in which case no fields are denied. */ - public Set getDeniedFields() { + public List getDeniedFields() { return deniedFields; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java index 6e4fff0708ddd..7b9cd16e65a0a 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java @@ -170,9 +170,9 @@ public static final class Builder { private @Nullable List privileges = null; private @Nullable - Collection grantedFields = null; + List grantedFields = null; private @Nullable - Collection deniedFields = null; + List deniedFields = null; private @Nullable String query = null; boolean allowRestrictedIndices = false; @@ -206,7 +206,7 @@ public Builder grantedFields(@Nullable String... grantedFields) { return grantedFields(Arrays.asList(grantedFields)); } - public Builder grantedFields(@Nullable Collection grantedFields) { + public Builder grantedFields(@Nullable List grantedFields) { this.grantedFields = grantedFields; return this; } @@ -219,7 +219,7 @@ public Builder deniedFields(@Nullable String... deniedFields) { return deniedFields(Arrays.asList(deniedFields)); } - public Builder deniedFields(@Nullable Collection deniedFields) { + public Builder deniedFields(@Nullable List deniedFields) { this.deniedFields = deniedFields; return this; } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java index 48a63dabfc3c1..7c1f26860ac37 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java @@ -42,8 +42,8 @@ */ public class UserIndicesPrivileges extends AbstractIndicesPrivileges { - private final Set fieldSecurity; - private final Set query; + private final List fieldSecurity; + private final List query; private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( "user_indices_privilege", true, UserIndicesPrivileges::buildObjectFromParserArgs); @@ -72,17 +72,17 @@ public static UserIndicesPrivileges fromXContent(XContentParser parser) throws I } public UserIndicesPrivileges(Collection indices, Collection privileges, boolean allowRestrictedIndices, - Collection fieldSecurity, Collection query) { + List fieldSecurity, List query) { super(indices, privileges, allowRestrictedIndices); - this.fieldSecurity = fieldSecurity == null ? Collections.emptySet() : Set.copyOf(fieldSecurity); - this.query = query == null ? Collections.emptySet() : Set.copyOf(query); + this.fieldSecurity = fieldSecurity == null ? Collections.emptyList() : List.copyOf(fieldSecurity); + this.query = query == null ? Collections.emptyList() : List.copyOf(query); } - public Set getFieldSecurity() { + public List getFieldSecurity() { return fieldSecurity; } - public Set getQueries() { + public List getQueries() { return query; } From 282be2b4183ee6bf21b1e87510131529b27e5ee7 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 22:39:13 -0400 Subject: [PATCH 13/20] Fix imports --- .../security/user/privileges/AbstractIndicesPrivileges.java | 1 - .../client/security/user/privileges/IndicesPrivileges.java | 1 - .../client/security/user/privileges/UserIndicesPrivileges.java | 1 - 3 files changed, 3 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java index 3c4a62b7f8529..99af2b20877b6 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/AbstractIndicesPrivileges.java @@ -33,7 +33,6 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.Set; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java index 7b9cd16e65a0a..2e845906696da 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/IndicesPrivileges.java @@ -29,7 +29,6 @@ import java.io.IOException; import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.Objects; diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java index 7c1f26860ac37..474030f9689d5 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/privileges/UserIndicesPrivileges.java @@ -28,7 +28,6 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.Set; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; From 7a01e7e9a30d118d8958c0c60f496fc28c6f3766 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 22 Apr 2019 23:04:53 -0400 Subject: [PATCH 14/20] Correct assertion messages --- .../org/elasticsearch/client/security/GetUsersResponse.java | 2 +- .../main/java/org/elasticsearch/client/security/user/User.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java index 775fbed3c3549..9c5bcaf7524a6 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java @@ -124,7 +124,7 @@ public ParsedUser(String username, List roles, Map metad @Nullable String fullName, @Nullable String email) { String checkedUsername = Objects.requireNonNull(username, "`username` is required, cannot be null"); List checkedRoles = - List.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); + List.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty list instead.")); Map checkedMetadata = Collections.unmodifiableMap( Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); this.user = new User(checkedUsername, checkedRoles, checkedMetadata, fullName, email); diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java index 82ecabc03b6d4..92ee4b51fe181 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/user/User.java @@ -51,7 +51,7 @@ public final class User { public User(String username, List roles, Map metadata, @Nullable String fullName, @Nullable String email) { this.username = Objects.requireNonNull(username, "`username` is required, cannot be null"); - this.roles = List.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")); + this.roles = List.copyOf(Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty list instead.")); this.metadata = Collections.unmodifiableMap( Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead.")); this.fullName = fullName; From ead000ace4861c85852370374893e778a7a2ee41 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Tue, 23 Apr 2019 07:06:00 -0400 Subject: [PATCH 15/20] Iteration --- .../common/io/stream/StreamOutput.java | 3 +- .../index/similarity/SimilarityProviders.java | 15 +-- .../transport/TransportService.java | 3 +- .../aggregations/AggregationsTests.java | 102 ++++++------------ 4 files changed, 43 insertions(+), 80 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java b/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java index 64474bde7ea67..431e00fcf063a 100644 --- a/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java +++ b/server/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java @@ -619,7 +619,8 @@ public final void writeOptionalInstant(@Nullable Instant instant) throws IOExcep o.writeByte((byte) 3); o.writeFloat((float) v); }), - entry(Double.class, + entry( + Double.class, (o, v) -> { o.writeByte((byte) 4); o.writeDouble((double) v); diff --git a/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java b/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java index ecf958c21d17a..135a3afee1ea5 100644 --- a/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java +++ b/server/src/main/java/org/elasticsearch/index/similarity/SimilarityProviders.java @@ -72,12 +72,14 @@ private SimilarityProviders() {} // no instantiation "if", new BasicModelIF(), "in", new BasicModelIn(), "ine", new BasicModelIne()); + // TODO: be and g and both based on the bose-einstein model. // Is there a better replacement for d and p which use the binomial model? private static final Map LEGACY_BASIC_MODELS = Map.of( "be", "g", "d", "ine", "p", "ine"); + private static final Map AFTER_EFFECTS = Map.of( "b", new AfterEffectB(), "l", new AfterEffectL()); @@ -89,14 +91,13 @@ private SimilarityProviders() {} // no instantiation "saturated", new IndependenceSaturated(), "chisquared", new IndependenceChiSquared()); - private static final Map DISTRIBUTIONS; - private static final Map LAMBDAS; + private static final Map DISTRIBUTIONS = Map.of( + "ll", new DistributionLL(), + "spl", new DistributionSPL()); - static { - DISTRIBUTIONS = Map.of("ll", new DistributionLL(), "spl", new DistributionSPL()); - - LAMBDAS = Map.of("df", new LambdaDF(), "ttf", new LambdaTTF()); - } + private static final Map LAMBDAS = Map.of( + "df", new LambdaDF(), + "ttf", new LambdaTTF()); /** * Parses the given Settings and creates the appropriate {@link BasicModel} diff --git a/server/src/main/java/org/elasticsearch/transport/TransportService.java b/server/src/main/java/org/elasticsearch/transport/TransportService.java index 529aedae653da..52a5a15e405b4 100644 --- a/server/src/main/java/org/elasticsearch/transport/TransportService.java +++ b/server/src/main/java/org/elasticsearch/transport/TransportService.java @@ -757,7 +757,8 @@ public TransportAddress[] addressesFromString(String address, int perAddressLimi */ public static final Set VALID_ACTION_PREFIXES = Set.of( "indices:admin", - "indices:monitor", "indices:data/write", + "indices:monitor", + "indices:data/write", "indices:data/read", "indices:internal", "cluster:admin", diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java b/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java index 673b6b8e9dc91..c8163539d4a55 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/AggregationsTests.java @@ -3,8 +3,7 @@ * 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 + * 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 * @@ -12,10 +11,8 @@ * * 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 + * "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. */ @@ -153,7 +150,7 @@ public class AggregationsTests extends ESTestCase { new InternalTopHitsTests(), new InternalCompositeTests(), new InternalMedianAbsoluteDeviationTests()); - + @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(InternalAggregationTestCase.getDefaultNamedXContents()); @@ -179,8 +176,7 @@ public void cleanUp() throws Exception { } public void testAllAggsAreBeingTested() { - assertEquals(InternalAggregationTestCase.getDefaultNamedXContents().size(), -aggsTests.size()); + assertEquals(InternalAggregationTestCase.getDefaultNamedXContents().size(), aggsTests.size()); Set aggs = aggsTests.stream().map((testCase) -> testCase.createTestInstance().getType()).collect(Collectors.toSet()); for (NamedXContentRegistry.Entry entry : InternalAggregationTestCase.getDefaultNamedXContents()) { assertTrue(aggs.contains(entry.name.getPreferredName())); @@ -198,47 +194,36 @@ public void testFromXContentWithRandomFields() throws IOException { /** * Test that parsing works for a randomly created Aggregations object with a * randomized aggregation tree. The test randomly chooses an - * {@link XContentType}, -randomizes the order of the {@link XContent} fields + * {@link XContentType}, randomizes the order of the {@link XContent} fields * and randomly sets the `humanReadable` flag when rendering the * {@link XContent}. * * @param addRandomFields - * if set, -this will also add random {@link XContent} fields to + * if set, this will also add random {@link XContent} fields to * tests that the parsers are lenient to future additions to rest * responses */ private void parseAndAssert(boolean addRandomFields) throws IOException { XContentType xContentType = randomFrom(XContentType.values()); - final ToXContent.Params params = new ToXContent.MapParams(singletonMap(RestSearchAction.TYPED_KEYS_PARAM, -"true")); + final ToXContent.Params params = new ToXContent.MapParams(singletonMap(RestSearchAction.TYPED_KEYS_PARAM, "true")); Aggregations aggregations = createTestInstance(); - BytesReference originalBytes = toShuffledXContent(aggregations, -xContentType, -params, -randomBoolean()); + BytesReference originalBytes = toShuffledXContent(aggregations, xContentType, params, randomBoolean()); BytesReference mutated; if (addRandomFields) { /* * - don't insert into the root object because it should only contain the named aggregations to test * - * - don't insert into the "meta" object, -because we pass on everything we find there + * - don't insert into the "meta" object, because we pass on everything we find there * - * - we don't want to directly insert anything random into "buckets" objects, -they are used with + * - we don't want to directly insert anything random into "buckets" objects, they are used with * "keyed" aggregations and contain named bucket objects. Any new named object on this level should * also be a bucket and be parsed as such. * - * - we cannot insert randomly into VALUE or VALUES objects e.g. in Percentiles, -the keys need to be numeric there + * - we cannot insert randomly into VALUE or VALUES objects e.g. in Percentiles, the keys need to be numeric there * - * - we cannot insert into ExtendedMatrixStats "covariance" or "correlation" fields, -their syntax is strict + * - we cannot insert into ExtendedMatrixStats "covariance" or "correlation" fields, their syntax is strict * - * - exclude "key", -it can be an array of objects and we need strict values + * - exclude "key", it can be an array of objects and we need strict values */ Predicate excludes = path -> (path.isEmpty() || path.endsWith("aggregations") || path.endsWith(Aggregation.CommonFields.META.getPreferredName()) @@ -246,30 +231,18 @@ private void parseAndAssert(boolean addRandomFields) throws IOException { || path.endsWith(CommonFields.VALUES.getPreferredName()) || path.endsWith("covariance") || path.endsWith("correlation") || path.contains(CommonFields.VALUE.getPreferredName()) || path.endsWith(CommonFields.KEY.getPreferredName())); - mutated = insertRandomFields(xContentType, -originalBytes, -excludes, -random()); + mutated = insertRandomFields(xContentType, originalBytes, excludes, random()); } else { mutated = originalBytes; } - try (XContentParser parser = createParser(xContentType.xContent(), -mutated)) { - assertEquals(XContentParser.Token.START_OBJECT, -parser.nextToken()); - assertEquals(XContentParser.Token.FIELD_NAME, -parser.nextToken()); - assertEquals(Aggregations.AGGREGATIONS_FIELD, -parser.currentName()); - assertEquals(XContentParser.Token.START_OBJECT, -parser.nextToken()); + try (XContentParser parser = createParser(xContentType.xContent(), mutated)) { + assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); + assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); + assertEquals(Aggregations.AGGREGATIONS_FIELD, parser.currentName()); + assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); Aggregations parsedAggregations = Aggregations.fromXContent(parser); - BytesReference parsedBytes = XContentHelper.toXContent(parsedAggregations, -xContentType, -randomBoolean()); - ElasticsearchAssertions.assertToXContentEquivalent(originalBytes, -parsedBytes, -xContentType); + BytesReference parsedBytes = XContentHelper.toXContent(parsedAggregations, xContentType, randomBoolean()); + ElasticsearchAssertions.assertToXContentEquivalent(originalBytes, parsedBytes, xContentType); } } @@ -282,28 +255,19 @@ public void testParsingExceptionOnUnknownAggregation() throws IOException { } builder.endObject(); BytesReference originalBytes = BytesReference.bytes(builder); - try (XContentParser parser = createParser(builder.contentType().xContent(), -originalBytes)) { - assertEquals(XContentParser.Token.START_OBJECT, -parser.nextToken()); - ParsingException ex = expectThrows(ParsingException.class, -() -> Aggregations.fromXContent(parser)); - assertEquals("Could not parse aggregation keyed as [unknownAggregation]", -ex.getMessage()); + try (XContentParser parser = createParser(builder.contentType().xContent(), originalBytes)) { + assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); + ParsingException ex = expectThrows(ParsingException.class, () -> Aggregations.fromXContent(parser)); + assertEquals("Could not parse aggregation keyed as [unknownAggregation]", ex.getMessage()); } } public final InternalAggregations createTestInstance() { - return createTestInstance(1, -0, -5); + return createTestInstance(1, 0, 5); } - private static InternalAggregations createTestInstance(final int minNumAggs, -final int currentDepth, -final int maxDepth) { - int numAggs = randomIntBetween(minNumAggs, -4); + private static InternalAggregations createTestInstance(final int minNumAggs, final int currentDepth, final int maxDepth) { + int numAggs = randomIntBetween(minNumAggs, 4); List aggs = new ArrayList<>(numAggs); for (int i = 0; i < numAggs; i++) { InternalAggregationTestCase testCase = randomFrom(aggsTests); @@ -311,9 +275,7 @@ private static InternalAggregations createTestInstance(final int minNumAggs, InternalMultiBucketAggregationTestCase multiBucketAggTestCase = (InternalMultiBucketAggregationTestCase) testCase; if (currentDepth < maxDepth) { multiBucketAggTestCase.setSubAggregationsSupplier( - () -> createTestInstance(0, -currentDepth + 1, -maxDepth) + () -> createTestInstance(0, currentDepth + 1, maxDepth) ); } else { multiBucketAggTestCase.setSubAggregationsSupplier( @@ -323,9 +285,7 @@ private static InternalAggregations createTestInstance(final int minNumAggs, } else if (testCase instanceof InternalSingleBucketAggregationTestCase) { InternalSingleBucketAggregationTestCase singleBucketAggTestCase = (InternalSingleBucketAggregationTestCase) testCase; if (currentDepth < maxDepth) { - singleBucketAggTestCase.subAggregationsSupplier = () -> createTestInstance(0, -currentDepth + 1, -maxDepth); + singleBucketAggTestCase.subAggregationsSupplier = () -> createTestInstance(0, currentDepth + 1, maxDepth); } else { singleBucketAggTestCase.subAggregationsSupplier = () -> InternalAggregations.EMPTY; } From 96dfcea997a012fa46e05189b010612f78bb81e9 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Tue, 23 Apr 2019 09:49:52 -0400 Subject: [PATCH 16/20] Fix tests --- .../client/security/GetUsersResponse.java | 22 +++++++++---------- .../security/GetPrivilegesResponseTests.java | 3 ++- .../security/GetUsersResponseTests.java | 16 +++++++------- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java index 9c5bcaf7524a6..6bc6f2ce2396f 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java @@ -27,12 +27,11 @@ import org.elasticsearch.common.xcontent.XContentParserUtils; import java.io.IOException; +import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; @@ -42,26 +41,27 @@ * Returns a List of {@link User} objects */ public class GetUsersResponse { - private final Set users; - private final Set enabledUsers; - public GetUsersResponse(Set users, Set enabledUsers) { - this.users = Collections.unmodifiableSet(users); - this.enabledUsers = Collections.unmodifiableSet(enabledUsers); + private final List users; + private final List enabledUsers; + + GetUsersResponse(List users, List enabledUsers) { + this.users = List.copyOf(users); + this.enabledUsers = List.copyOf(enabledUsers); } - public Set getUsers() { + public List getUsers() { return users; } - public Set getEnabledUsers() { + public List getEnabledUsers() { return enabledUsers; } public static GetUsersResponse fromXContent(XContentParser parser) throws IOException { XContentParserUtils.ensureExpectedToken(Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation); - final Set users = new HashSet<>(); - final Set enabledUsers = new HashSet<>(); + final List users = new ArrayList<>(); + final List enabledUsers = new ArrayList<>(); Token token; while ((token = parser.nextToken()) != Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(Token.FIELD_NAME, token, parser::getTokenLocation); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetPrivilegesResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetPrivilegesResponseTests.java index 74211892a09e8..bf55e224095fe 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetPrivilegesResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetPrivilegesResponseTests.java @@ -31,6 +31,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -139,7 +140,7 @@ public void testEqualsHashCode() { private static GetPrivilegesResponse mutateTestItem(GetPrivilegesResponse original) { if (randomBoolean()) { Set originalPrivileges = original.getPrivileges(); - List privileges = new ArrayList<>(); + Set privileges = new HashSet<>(); privileges.addAll(originalPrivileges); privileges.add(new ApplicationPrivilege("testapp", "all", Arrays.asList("action:login", "data:read/*", "manage:*"), null)); return new GetPrivilegesResponse(privileges); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java index 69db584287ceb..efaf78171b38d 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java @@ -91,8 +91,8 @@ private XContentBuilder toXContent(GetUsersResponse response, XContentBuilder bu } private static GetUsersResponse createTestInstance() { - final Set users = new HashSet<>(); - final Set enabledUsers = new HashSet<>(); + final List users = new ArrayList<>(); + final List enabledUsers = new ArrayList<>(); Map metadata = new HashMap<>(); metadata.put(randomAlphaOfLengthBetween(1, 5), randomInt()); @@ -113,8 +113,8 @@ private static GetUsersResponse createTestInstance() { } public void testEqualsHashCode() { - final Set users = new HashSet<>(); - final Set enabledUsers = new HashSet<>(); + final List users = new ArrayList<>(); + final List enabledUsers = new ArrayList<>(); Map metadata = new HashMap<>(); metadata.put("intelligence", 1); final User user1 = new User("testUser1", Arrays.asList(new String[] {"admin", "other_role1"}), @@ -140,8 +140,8 @@ public void testEqualsHashCode() { private static GetUsersResponse mutateTestItem(GetUsersResponse original) { if (randomBoolean()) { - final Set users = new HashSet<>(); - final Set enabledUsers = new HashSet<>(); + final List users = new ArrayList<>(); + final List enabledUsers = new ArrayList<>(); Map metadata = new HashMap<>(); metadata.put("intelligence", 1); final User user1 = new User("testUser1", Arrays.asList(new String[] {"admin", "other_role1"}), @@ -154,8 +154,8 @@ private static GetUsersResponse mutateTestItem(GetUsersResponse original) { metadata.put("intelligence", 5); // change intelligence final User user1 = new User("testUser1", Arrays.asList(new String[] {"admin", "other_role1"}), metadata, "Test User 1", null); - Set newUsers = original.getUsers().stream().collect(Collectors.toSet()); - Set enabledUsers = original.getEnabledUsers().stream().collect(Collectors.toSet()); + List newUsers = new ArrayList<>(original.getUsers()); + List enabledUsers = new ArrayList<>(original.getEnabledUsers()); newUsers.clear(); enabledUsers.clear(); newUsers.add(user1); From 874249f8af17ea3a65a37be81a00ab531004ea6b Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Tue, 23 Apr 2019 13:50:38 -0400 Subject: [PATCH 17/20] Reliable ordering --- .../authz/privilege/ApplicationPrivilegeDescriptor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilegeDescriptor.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilegeDescriptor.java index 613f64f93b54a..d80e2a1904558 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilegeDescriptor.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilegeDescriptor.java @@ -18,7 +18,7 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -167,7 +167,7 @@ private Builder privilegeName(String privilegeName) { } private Builder actions(Collection actions) { - this.actions = new HashSet<>(actions); + this.actions = new LinkedHashSet<>(actions); return this; } From 2d4ab87dca2517a3b8a9dd17ff872ca45f2c11d7 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Tue, 23 Apr 2019 14:10:42 -0400 Subject: [PATCH 18/20] Imports --- .../elasticsearch/client/security/GetUsersResponseTests.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java index efaf78171b38d..86f5387ff84cd 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java @@ -31,12 +31,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.function.Predicate; -import java.util.stream.Collectors; import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester; From 0cbfaec6b9731fb83f2cc4211542e2e68f68344b Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Fri, 26 Apr 2019 09:01:58 -0400 Subject: [PATCH 19/20] Fix tests --- .../client/security/GetUsersResponse.java | 23 +++++++++++------ .../security/GetUsersResponseTests.java | 25 +++++++++++-------- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java index 6bc6f2ce2396f..d4e325749a847 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/GetUsersResponse.java @@ -28,10 +28,13 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; @@ -42,20 +45,20 @@ */ public class GetUsersResponse { - private final List users; - private final List enabledUsers; + private final Map users; + private final Map enabledUsers; - GetUsersResponse(List users, List enabledUsers) { - this.users = List.copyOf(users); - this.enabledUsers = List.copyOf(enabledUsers); + GetUsersResponse(final Map users, final Map enabledUsers) { + this.users = Map.copyOf(users); + this.enabledUsers = Map.copyOf(enabledUsers); } public List getUsers() { - return users; + return List.copyOf(users.values()); } public List getEnabledUsers() { - return enabledUsers; + return List.copyOf(enabledUsers.values()); } public static GetUsersResponse fromXContent(XContentParser parser) throws IOException { @@ -71,7 +74,11 @@ public static GetUsersResponse fromXContent(XContentParser parser) throws IOExce enabledUsers.add(parsedUser.user); } } - return new GetUsersResponse(users, enabledUsers); + return new GetUsersResponse(toMap(users), toMap(enabledUsers)); + } + + static Map toMap(final Collection users) { + return users.stream().collect(Collectors.toUnmodifiableMap(User::getUsername, Function.identity())); } @Override diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java index 86f5387ff84cd..1c30760ee53a3 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetUsersResponseTests.java @@ -35,6 +35,7 @@ import java.util.Map; import java.util.function.Predicate; +import static org.elasticsearch.client.security.GetUsersResponse.toMap; import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester; /** tests the Response for getting users from the security HLRC */ @@ -106,7 +107,7 @@ private static GetUsersResponse createTestInstance() { Arrays.asList(new String[] {randomAlphaOfLength(5), randomAlphaOfLength(5)}), metadata2, randomAlphaOfLength(10), null); users.add(user2); - return new GetUsersResponse(users, enabledUsers); + return new GetUsersResponse(toMap(users), toMap(enabledUsers)); } public void testEqualsHashCode() { @@ -122,17 +123,18 @@ public void testEqualsHashCode() { metadata2.put("intelligence", 9); metadata2.put("specialty", "geo"); final User user2 = new User("testUser2", Arrays.asList(new String[] {"admin"}), - metadata, "Test User 2", "testuser2@example.com"); + metadata2, "Test User 2", "testuser2@example.com"); users.add(user2); enabledUsers.add(user2); - final GetUsersResponse getUsersResponse = new GetUsersResponse(users, enabledUsers); + final GetUsersResponse getUsersResponse = new GetUsersResponse(toMap(users), toMap(enabledUsers)); assertNotNull(getUsersResponse); - EqualsHashCodeTestUtils.checkEqualsAndHashCode(getUsersResponse, (original) -> { - return new GetUsersResponse(original.getUsers(), original.getEnabledUsers()); - }); - EqualsHashCodeTestUtils.checkEqualsAndHashCode(getUsersResponse, (original) -> { - return new GetUsersResponse(original.getUsers(), original.getEnabledUsers()); - }, GetUsersResponseTests::mutateTestItem); + EqualsHashCodeTestUtils.checkEqualsAndHashCode( + getUsersResponse, + (original) -> new GetUsersResponse(toMap(original.getUsers()), toMap(original.getEnabledUsers()))); + EqualsHashCodeTestUtils.checkEqualsAndHashCode( + getUsersResponse, + (original) -> new GetUsersResponse(toMap(original.getUsers()), toMap(original.getEnabledUsers())), + GetUsersResponseTests::mutateTestItem); } private static GetUsersResponse mutateTestItem(GetUsersResponse original) { @@ -145,7 +147,7 @@ private static GetUsersResponse mutateTestItem(GetUsersResponse original) { metadata, "Test User 1", null); users.add(user1); enabledUsers.add(user1); - return new GetUsersResponse(users, enabledUsers); + return new GetUsersResponse(toMap(users), toMap(enabledUsers)); } Map metadata = new HashMap<>(); metadata.put("intelligence", 5); // change intelligence @@ -157,6 +159,7 @@ private static GetUsersResponse mutateTestItem(GetUsersResponse original) { enabledUsers.clear(); newUsers.add(user1); enabledUsers.add(user1); - return new GetUsersResponse(newUsers, enabledUsers); + return new GetUsersResponse(toMap(newUsers), toMap(enabledUsers)); } + } From baeee027b886298e6d1944ed39af27e2c1e392dd Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Fri, 26 Apr 2019 10:25:30 -0400 Subject: [PATCH 20/20] Fix test --- .../client/documentation/SecurityDocumentationIT.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java index 9c6b04821a164..f9a1c5c6571eb 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java @@ -104,6 +104,7 @@ import java.util.Arrays; import java.util.Base64; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -159,6 +160,7 @@ public void testGetUsers() throws Exception { List users = new ArrayList<>(3); users.addAll(response.getUsers()); + users.sort(Comparator.comparing(User::getUsername)); assertNotNull(response); assertThat(users.size(), equalTo(3)); assertThat(users.get(0).getUsername(), equalTo(usernames[0]));