diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/indices/common/RoundingBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/indices/common/RoundingBenchmark.java index 9efcfef8088ee..7ee8c33b2fe8e 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/indices/common/RoundingBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/indices/common/RoundingBenchmark.java @@ -89,16 +89,11 @@ public void buildDates() { roundingBuilder = Rounding.builder(TimeValue.parseTimeValue(interval, "interval")); } Rounding rounding = roundingBuilder.timeZone(ZoneId.of(zone)).build(); - switch (rounder) { - case "java time": - rounderBuilder = rounding::prepareJavaTime; - break; - case "es": - rounderBuilder = () -> rounding.prepare(min, max); - break; - default: - throw new IllegalArgumentException("Expectd rounder to be [java time] or [es]"); - } + rounderBuilder = switch (rounder) { + case "java time" -> rounding::prepareJavaTime; + case "es" -> () -> rounding.prepare(min, max); + default -> throw new IllegalArgumentException("Expected rounder to be [java time] or [es]"); + }; } @Benchmark diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/script/ScriptScoreBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/script/ScriptScoreBenchmark.java index 05ac262c533e5..2a356b7883a02 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/script/ScriptScoreBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/script/ScriptScoreBenchmark.java @@ -101,28 +101,19 @@ public class ScriptScoreBenchmark { @Setup public void setupScript() { - switch (script) { - case "expression": - factory = scriptModule.engines.get("expression").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of()); - break; - case "metal": - factory = bareMetalScript(); - break; - case "painless_cast": - factory = scriptModule.engines.get("painless") - .compile( - "test", - "((org.elasticsearch.index.fielddata.ScriptDocValues.Longs)doc['n']).value", - ScoreScript.CONTEXT, - Map.of() - ); - break; - case "painless_def": - factory = scriptModule.engines.get("painless").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of()); - break; - default: - throw new IllegalArgumentException("Don't know how to implement script [" + script + "]"); - } + factory = switch (script) { + case "expression" -> scriptModule.engines.get("expression").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of()); + case "metal" -> bareMetalScript(); + case "painless_cast" -> scriptModule.engines.get("painless") + .compile( + "test", + "((org.elasticsearch.index.fielddata.ScriptDocValues.Longs)doc['n']).value", + ScoreScript.CONTEXT, + Map.of() + ); + case "painless_def" -> scriptModule.engines.get("painless").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of()); + default -> throw new IllegalArgumentException("Don't know how to implement script [" + script + "]"); + }; } @Setup diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java index 43a2d1930d0e8..18a165dc87830 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java @@ -107,20 +107,12 @@ public class AggConstructionContentionBenchmark { @Setup public void setup() { - switch (breaker) { - case "real": - breakerService = new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings); - break; - case "preallocate": - preallocateBreaker = true; - breakerService = new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings); - break; - case "noop": - breakerService = new NoneCircuitBreakerService(); - break; - default: - throw new UnsupportedOperationException(); - } + breakerService = switch (breaker) { + case "real", "preallocate" -> new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings); + case "noop" -> new NoneCircuitBreakerService(); + default -> throw new UnsupportedOperationException(); + }; + preallocateBreaker = breaker.equals("preallocate"); bigArrays = new BigArrays(recycler, breakerService, "request"); } diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/search/fetch/subphase/FetchSourcePhaseBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/search/fetch/subphase/FetchSourcePhaseBenchmark.java index 776d2aa9fedfe..ae287aefff5f8 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/search/fetch/subphase/FetchSourcePhaseBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/search/fetch/subphase/FetchSourcePhaseBenchmark.java @@ -53,22 +53,13 @@ public class FetchSourcePhaseBenchmark { @Setup public void setup() throws IOException { - switch (source) { - case "tiny": - sourceBytes = new BytesArray("{\"message\": \"short\"}"); - break; - case "short": - sourceBytes = read300BytesExample(); - break; - case "one_4k_field": - sourceBytes = buildBigExample("huge".repeat(1024)); - break; - case "one_4m_field": - sourceBytes = buildBigExample("huge".repeat(1024 * 1024)); - break; - default: - throw new IllegalArgumentException("Unknown source [" + source + "]"); - } + sourceBytes = switch (source) { + case "tiny" -> new BytesArray("{\"message\": \"short\"}"); + case "short" -> read300BytesExample(); + case "one_4k_field" -> buildBigExample("huge".repeat(1024)); + case "one_4m_field" -> buildBigExample("huge".repeat(1024 * 1024)); + default -> throw new IllegalArgumentException("Unknown source [" + source + "]"); + }; fetchContext = new FetchSourceContext( true, Strings.splitStringByCommaToArray(includes), diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/SymbolicLinkPreservingTar.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/SymbolicLinkPreservingTar.java index 55d325fbde2c4..29c7dfd422547 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/SymbolicLinkPreservingTar.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/SymbolicLinkPreservingTar.java @@ -44,18 +44,11 @@ public class SymbolicLinkPreservingTar extends Tar { @Override protected CopyAction createCopyAction() { - final ArchiveOutputStreamFactory compressor; - switch (getCompression()) { - case BZIP2: - compressor = Bzip2Archiver.getCompressor(); - break; - case GZIP: - compressor = GzipArchiver.getCompressor(); - break; - default: - compressor = new SimpleCompressor(); - break; - } + final ArchiveOutputStreamFactory compressor = switch (getCompression()) { + case BZIP2 -> Bzip2Archiver.getCompressor(); + case GZIP -> GzipArchiver.getCompressor(); + default -> new SimpleCompressor(); + }; return new SymbolicLinkPreservingTarCopyAction(getArchiveFile(), compressor, isPreserveFileTimestamps()); } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java index a8aa68641fd37..4be9380388a74 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java @@ -87,23 +87,17 @@ static List transformConfig(List lines) { } switch (keyParts[2]) { - case "type": + case "type" -> { if (value.equals("RollingFile")) { value = "Console"; } line = key + " = " + value; - break; - - case "fileName": - case "filePattern": - case "policies": - case "strategy": + } + case "fileName", "filePattern", "policies", "strategy" -> { // No longer applicable. Omit it. skipNext = line.endsWith("\\"); continue; - - default: - break; + } } } else if (line.startsWith("rootLogger.appenderRef")) { String[] parts = line.split("\\s*=\\s*"); diff --git a/build-tools/src/main/java/org/elasticsearch/gradle/Architecture.java b/build-tools/src/main/java/org/elasticsearch/gradle/Architecture.java index ccc81954aabcb..665568e337376 100644 --- a/build-tools/src/main/java/org/elasticsearch/gradle/Architecture.java +++ b/build-tools/src/main/java/org/elasticsearch/gradle/Architecture.java @@ -21,15 +21,11 @@ public enum Architecture { public static Architecture current() { final String architecture = System.getProperty("os.arch", ""); - switch (architecture) { - case "amd64": - case "x86_64": - return X64; - case "aarch64": - return AARCH64; - default: - throw new IllegalArgumentException("can not determine architecture from [" + architecture + "]"); - } + return switch (architecture) { + case "amd64", "x86_64" -> X64; + case "aarch64" -> AARCH64; + default -> throw new IllegalArgumentException("can not determine architecture from [" + architecture + "]"); + }; } } diff --git a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/AbstractBenchmark.java b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/AbstractBenchmark.java index ba675c6323a8b..92f6e61636f50 100644 --- a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/AbstractBenchmark.java +++ b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/AbstractBenchmark.java @@ -36,16 +36,12 @@ public final void run(String[] args) throws Exception { System.exit(1); } switch (args[0]) { - case "search": - runSearchBenchmark(args); - break; - case "bulk": - runBulkIndexBenchmark(args); - break; - default: + case "search" -> runSearchBenchmark(args); + case "bulk" -> runBulkIndexBenchmark(args); + default -> { System.err.println("Unknown benchmark type [" + args[0] + "]"); System.exit(1); - + } } } diff --git a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkMain.java b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkMain.java index b7173365f9fd3..e2afd828fd7af 100644 --- a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkMain.java +++ b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkMain.java @@ -16,15 +16,14 @@ public class BenchmarkMain { @SuppressForbidden(reason = "system out is ok for a command line tool") public static void main(String[] args) throws Exception { String type = args[0]; - AbstractBenchmark benchmark = null; - switch (type) { - case "rest": - benchmark = new RestClientBenchmark(); - break; - default: + AbstractBenchmark benchmark = switch (type) { + case "rest" -> new RestClientBenchmark(); + default -> { System.err.println("Unknown client type [" + type + "]"); System.exit(1); - } + yield null; + } + }; benchmark.run(Arrays.copyOfRange(args, 1, args.length)); } } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java index 0d8fbfef0d73e..5d2dcef83cf7b 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java @@ -163,14 +163,11 @@ public String getName() { } public static Status fromString(String value) { - switch (value) { - case "active": - return Status.ACTIVE; - case "paused": - return Status.PAUSED; - default: - throw new IllegalArgumentException("unexpected status value [" + value + "]"); - } + return switch (value) { + case "active" -> Status.ACTIVE; + case "paused" -> Status.PAUSED; + default -> throw new IllegalArgumentException("unexpected status value [" + value + "]"); + }; } } } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java index a77621328fdd2..1d922a7f641e4 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java @@ -149,20 +149,11 @@ private static IndexEntry parseIndexEntry(XContentParser parser) throws IOExcept parser.nextToken(); if (parser.currentToken() == Token.START_OBJECT) { switch (parser.currentName()) { - case "aliases": - indexAliases = parseAliases(parser); - break; - case "mappings": - indexMappings = parseMappings(parser); - break; - case "settings": - indexSettings = Settings.fromXContent(parser); - break; - case "defaults": - indexDefaultSettings = Settings.fromXContent(parser); - break; - default: - parser.skipChildren(); + case "aliases" -> indexAliases = parseAliases(parser); + case "mappings" -> indexMappings = parseMappings(parser); + case "settings" -> indexSettings = Settings.fromXContent(parser); + case "defaults" -> indexDefaultSettings = Settings.fromXContent(parser); + default -> parser.skipChildren(); } } else if (parser.currentToken() == Token.VALUE_STRING) { if (parser.currentName().equals("data_stream")) { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicenseStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicenseStatus.java index 5973601f07c29..3038b702c84e2 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicenseStatus.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicenseStatus.java @@ -27,15 +27,11 @@ public String label() { } public static LicenseStatus fromString(String value) { - switch (value) { - case "active": - return ACTIVE; - case "invalid": - return INVALID; - case "expired": - return EXPIRED; - default: - throw new IllegalArgumentException("unknown license status [" + value + "]"); - } + return switch (value) { + case "active" -> ACTIVE; + case "invalid" -> INVALID; + case "expired" -> EXPIRED; + default -> throw new IllegalArgumentException("unknown license status [" + value + "]"); + }; } } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java index 8f6e03cd8533c..f9dbaf611ec11 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java @@ -42,15 +42,11 @@ public String toString() { } public static LicensesStatus fromString(String value) { - switch (value) { - case "valid": - return VALID; - case "invalid": - return INVALID; - case "expired": - return EXPIRED; - default: - throw new IllegalArgumentException("unknown licenses status [" + value + "]"); - } + return switch (value) { + case "valid" -> VALID; + case "invalid" -> INVALID; + case "expired" -> EXPIRED; + default -> throw new IllegalArgumentException("unknown licenses status [" + value + "]"); + }; } } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/parser/RoleMapperExpressionParser.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/parser/RoleMapperExpressionParser.java index eb0d748ca444d..fb5a91fde7f51 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/parser/RoleMapperExpressionParser.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/security/support/expressiondsl/parser/RoleMapperExpressionParser.java @@ -164,25 +164,16 @@ private List parseArray(ParseField field, XContentParser parser, CheckedF } private Object parseFieldValue(XContentParser parser) throws IOException { - switch (parser.currentToken()) { - case VALUE_STRING: - return parser.text(); - - case VALUE_BOOLEAN: - return parser.booleanValue(); - - case VALUE_NUMBER: - return parser.longValue(); - - case VALUE_NULL: - return null; - - default: - throw new ElasticsearchParseException( - "failed to parse rules expression. expected a field value but found [{}] instead", - parser.currentToken() - ); - } + return switch (parser.currentToken()) { + case VALUE_STRING -> parser.text(); + case VALUE_BOOLEAN -> parser.booleanValue(); + case VALUE_NUMBER -> parser.longValue(); + case VALUE_NULL -> null; + default -> throw new ElasticsearchParseException( + "failed to parse rules expression. expected a field value but found [{}] instead", + parser.currentToken() + ); + }; } } diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfig.java index 13b816c98e244..1a6b8c1a4751d 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfig.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfig.java @@ -75,24 +75,17 @@ public static GroupConfig fromXContent(final XContentParser parser) throws IOExc continue; } - SingleGroupSource groupSource = null; - switch (groupType) { - case "terms": - groupSource = TermsGroupSource.fromXContent(parser); - break; - case "histogram": - groupSource = HistogramGroupSource.fromXContent(parser); - break; - case "date_histogram": - groupSource = DateHistogramGroupSource.fromXContent(parser); - break; - case "geotile_grid": - groupSource = GeoTileGroupSource.fromXContent(parser); - break; - default: + SingleGroupSource groupSource = switch (groupType) { + case "terms" -> TermsGroupSource.fromXContent(parser); + case "histogram" -> HistogramGroupSource.fromXContent(parser); + case "date_histogram" -> DateHistogramGroupSource.fromXContent(parser); + case "geotile_grid" -> GeoTileGroupSource.fromXContent(parser); + default -> { // not a valid group source. Consume up to the dest field end object consumeUntilEndObject(parser, 2); - } + yield null; + } + }; if (groupSource != null) { groups.put(destinationFieldName, groupSource); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/ClusterRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/ClusterRequestConvertersTests.java index 80918050971cf..5e7c9c96529b1 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/ClusterRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/ClusterRequestConvertersTests.java @@ -69,29 +69,28 @@ public void testClusterHealth() { String timeout = ESTestCase.randomTimeValue(); String masterTimeout = ESTestCase.randomTimeValue(); switch (timeoutType) { - case "timeout": + case "timeout" -> { healthRequest.timeout(timeout); expectedParams.put("timeout", timeout); // If Master Timeout wasn't set it uses the same value as Timeout expectedParams.put("master_timeout", timeout); - break; - case "masterTimeout": + } + case "masterTimeout" -> { expectedParams.put("timeout", "30s"); healthRequest.masterNodeTimeout(masterTimeout); expectedParams.put("master_timeout", masterTimeout); - break; - case "both": + } + case "both" -> { healthRequest.timeout(timeout); expectedParams.put("timeout", timeout); healthRequest.masterNodeTimeout(timeout); expectedParams.put("master_timeout", timeout); - break; - case "none": + } + case "none" -> { expectedParams.put("timeout", "30s"); expectedParams.put("master_timeout", "30s"); - break; - default: - throw new UnsupportedOperationException(); + } + default -> throw new UnsupportedOperationException(); } RequestConvertersTests.setRandomWaitForActiveShards(healthRequest::waitForActiveShards, ActiveShardCount.NONE, expectedParams); if (ESTestCase.randomBoolean()) { diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RollupIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RollupIT.java index 3d65a176a7475..2183d93a5c903 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RollupIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RollupIT.java @@ -355,20 +355,11 @@ public void testGetRollupCaps() throws Exception { List> timestampCaps = fieldCaps.get("date").getAggs(); for (Map.Entry entry : timestampCaps.get(0).entrySet()) { switch (entry.getKey()) { - case "agg": - assertThat(entry.getValue(), equalTo("date_histogram")); - break; - case "delay": - assertThat(entry.getValue(), equalTo("foo")); - break; - case "calendar_interval": - assertThat(entry.getValue(), equalTo("1d")); - break; - case "time_zone": - assertThat(entry.getValue(), equalTo("UTC")); - break; - default: - fail("Unknown field cap: [" + entry.getKey() + "]"); + case "agg" -> assertThat(entry.getValue(), equalTo("date_histogram")); + case "delay" -> assertThat(entry.getValue(), equalTo("foo")); + case "calendar_interval" -> assertThat(entry.getValue(), equalTo("1d")); + case "time_zone" -> assertThat(entry.getValue(), equalTo("UTC")); + default -> fail("Unknown field cap: [" + entry.getKey() + "]"); } } @@ -469,20 +460,11 @@ public void testGetRollupIndexCaps() throws Exception { List> timestampCaps = fieldCaps.get("date").getAggs(); for (Map.Entry entry : timestampCaps.get(0).entrySet()) { switch (entry.getKey()) { - case "agg": - assertThat(entry.getValue(), equalTo("date_histogram")); - break; - case "delay": - assertThat(entry.getValue(), equalTo("foo")); - break; - case "calendar_interval": - assertThat(entry.getValue(), equalTo("1d")); - break; - case "time_zone": - assertThat(entry.getValue(), equalTo("UTC")); - break; - default: - fail("Unknown field cap: [" + entry.getKey() + "]"); + case "agg" -> assertThat(entry.getValue(), equalTo("date_histogram")); + case "delay" -> assertThat(entry.getValue(), equalTo("foo")); + case "calendar_interval" -> assertThat(entry.getValue(), equalTo("1d")); + case "time_zone" -> assertThat(entry.getValue(), equalTo("UTC")); + default -> fail("Unknown field cap: [" + entry.getKey() + "]"); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/XPackRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/XPackRequestConvertersTests.java index abf003f61e2a4..40e71c0231b61 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/XPackRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/XPackRequestConvertersTests.java @@ -27,19 +27,16 @@ public void testXPackInfo() { } int option = ESTestCase.between(0, 2); switch (option) { - case 0: - infoRequest.setCategories(EnumSet.allOf(XPackInfoRequest.Category.class)); - break; - case 1: + case 0 -> infoRequest.setCategories(EnumSet.allOf(XPackInfoRequest.Category.class)); + case 1 -> { infoRequest.setCategories(EnumSet.of(XPackInfoRequest.Category.FEATURES)); expectedParams.put("categories", "features"); - break; - case 2: + } + case 2 -> { infoRequest.setCategories(EnumSet.of(XPackInfoRequest.Category.FEATURES, XPackInfoRequest.Category.BUILD)); expectedParams.put("categories", "build,features"); - break; - default: - throw new IllegalArgumentException("invalid option [" + option + "]"); + } + default -> throw new IllegalArgumentException("invalid option [" + option + "]"); } Request request = XPackRequestConverters.info(infoRequest); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/eql/EqlSearchResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/eql/EqlSearchResponseTests.java index 4a3a3ed85ca10..aa611ed64cee5 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/eql/EqlSearchResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/eql/EqlSearchResponseTests.java @@ -116,17 +116,19 @@ static List randomEv private static Tuple randomDocumentField(XContentType xType) { switch (randomIntBetween(0, 2)) { - case 0: + case 0 -> { String fieldName = randomAlphaOfLengthBetween(3, 10); Tuple, List> tuple = RandomObjects.randomStoredFieldValues(random(), xType); DocumentField input = new DocumentField(fieldName, tuple.v1()); DocumentField expected = new DocumentField(fieldName, tuple.v2()); return Tuple.tuple(input, expected); - case 1: + } + case 1 -> { List listValues = randomList(1, 5, () -> randomList(1, 5, ESTestCase::randomInt)); DocumentField listField = new DocumentField(randomAlphaOfLength(5), listValues); return Tuple.tuple(listField, listField); - case 2: + } + case 2 -> { List objectValues = randomList( 1, 5, @@ -141,8 +143,8 @@ private static Tuple randomDocumentField(XContentT ); DocumentField objectField = new DocumentField(randomAlphaOfLength(5), objectValues); return Tuple.tuple(objectField, objectField); - default: - throw new IllegalStateException(); + } + default -> throw new IllegalStateException(); } } @@ -212,14 +214,11 @@ private static List> getKeysGenerators() { public static org.elasticsearch.xpack.eql.action.EqlSearchResponse createRandomInstance(TotalHits totalHits, XContentType xType) { int type = between(0, 1); - switch (type) { - case 0: - return createRandomEventsResponse(totalHits, xType); - case 1: - return createRandomSequencesResponse(totalHits, xType); - default: - return null; - } + return switch (type) { + case 0 -> createRandomEventsResponse(totalHits, xType); + case 1 -> createRandomSequencesResponse(totalHits, xType); + default -> null; + }; } @Override diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/ExplainLifecycleRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/ExplainLifecycleRequestTests.java index 7cc0751c23f8e..a6bdac2f5c02b 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/ExplainLifecycleRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/ExplainLifecycleRequestTests.java @@ -49,29 +49,24 @@ private ExplainLifecycleRequest mutateInstance(ExplainLifecycleRequest instance) String[] indices = instance.getIndices(); IndicesOptions indicesOptions = instance.indicesOptions(); switch (between(0, 1)) { - case 0: - indices = randomValueOtherThanMany( - i -> Arrays.equals(i, instance.getIndices()), - () -> generateRandomStringArray(20, 10, false, false) - ); - break; - case 1: - indicesOptions = randomValueOtherThan( - indicesOptions, - () -> IndicesOptions.fromOptions( - randomBoolean(), - randomBoolean(), - randomBoolean(), - randomBoolean(), - randomBoolean(), - randomBoolean(), - randomBoolean(), - randomBoolean() - ) - ); - break; - default: - throw new AssertionError("Illegal randomisation branch"); + case 0 -> indices = randomValueOtherThanMany( + i -> Arrays.equals(i, instance.getIndices()), + () -> generateRandomStringArray(20, 10, false, false) + ); + case 1 -> indicesOptions = randomValueOtherThan( + instance.indicesOptions(), + () -> IndicesOptions.fromOptions( + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean() + ) + ); + default -> throw new AssertionError("Illegal randomisation branch"); } ExplainLifecycleRequest newRequest = new ExplainLifecycleRequest(indices); newRequest.indicesOptions(indicesOptions); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/LifecyclePolicyTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/LifecyclePolicyTests.java index 8335a51a71b5f..f70346490991b 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/LifecyclePolicyTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/ilm/LifecyclePolicyTests.java @@ -226,60 +226,37 @@ public static LifecyclePolicy createRandomPolicy(String lifecycleName) { List phaseNames = Arrays.asList("hot", "warm", "cold", "delete"); Map phases = new HashMap<>(phaseNames.size()); Function> validActions = (phase) -> { - switch (phase) { - case "hot": - return VALID_HOT_ACTIONS; - case "warm": - return VALID_WARM_ACTIONS; - case "cold": - return VALID_COLD_ACTIONS; - case "delete": - return VALID_DELETE_ACTIONS; - default: - throw new IllegalArgumentException("invalid phase [" + phase + "]"); - } + return switch (phase) { + case "hot" -> VALID_HOT_ACTIONS; + case "warm" -> VALID_WARM_ACTIONS; + case "cold" -> VALID_COLD_ACTIONS; + case "delete" -> VALID_DELETE_ACTIONS; + default -> throw new IllegalArgumentException("invalid phase [" + phase + "]"); + }; }; Function allowEmptyActions = (phase) -> { - switch (phase) { - case "hot": - case "warm": - case "cold": - return true; - case "delete": - return false; - default: - throw new IllegalArgumentException("invalid phase [" + phase + "]"); - } + return switch (phase) { + case "hot", "warm", "cold" -> true; + case "delete" -> false; + default -> throw new IllegalArgumentException("invalid phase [" + phase + "]"); + }; }; Function randomAction = (action) -> { - switch (action) { - case AllocateAction.NAME: - return AllocateActionTests.randomInstance(); - case DeleteAction.NAME: - return new DeleteAction(); - case ForceMergeAction.NAME: - return ForceMergeActionTests.randomInstance(); - case ReadOnlyAction.NAME: - return new ReadOnlyAction(); - case RolloverAction.NAME: - return RolloverActionTests.randomInstance(); - case ShrinkAction.NAME: - return ShrinkActionTests.randomInstance(); - case FreezeAction.NAME: - return new FreezeAction(); - case WaitForSnapshotAction.NAME: - return WaitForSnapshotActionTests.randomInstance(); - case SetPriorityAction.NAME: - return SetPriorityActionTests.randomInstance(); - case UnfollowAction.NAME: - return new UnfollowAction(); - case SearchableSnapshotAction.NAME: - return new SearchableSnapshotAction("repo", randomBoolean()); - case MigrateAction.NAME: - return new MigrateAction(randomBoolean()); - default: - throw new IllegalArgumentException("invalid action [" + action + "]"); - } + return switch (action) { + case AllocateAction.NAME -> AllocateActionTests.randomInstance(); + case DeleteAction.NAME -> new DeleteAction(); + case ForceMergeAction.NAME -> ForceMergeActionTests.randomInstance(); + case ReadOnlyAction.NAME -> new ReadOnlyAction(); + case RolloverAction.NAME -> RolloverActionTests.randomInstance(); + case ShrinkAction.NAME -> ShrinkActionTests.randomInstance(); + case FreezeAction.NAME -> new FreezeAction(); + case WaitForSnapshotAction.NAME -> WaitForSnapshotActionTests.randomInstance(); + case SetPriorityAction.NAME -> SetPriorityActionTests.randomInstance(); + case UnfollowAction.NAME -> new UnfollowAction(); + case SearchableSnapshotAction.NAME -> new SearchableSnapshotAction("repo", randomBoolean()); + case MigrateAction.NAME -> new MigrateAction(randomBoolean()); + default -> throw new IllegalArgumentException("invalid action [" + action + "]"); + }; }; TimeValue prev = null; boolean searchableSnapshotSeen = false; @@ -318,33 +295,20 @@ public static LifecyclePolicy createRandomPolicy(String lifecycleName) { } private LifecycleAction getTestAction(String actionName) { - switch (actionName) { - case AllocateAction.NAME: - return AllocateActionTests.randomInstance(); - case DeleteAction.NAME: - return new DeleteAction(); - case ForceMergeAction.NAME: - return ForceMergeActionTests.randomInstance(); - case ReadOnlyAction.NAME: - return new ReadOnlyAction(); - case RolloverAction.NAME: - return RolloverActionTests.randomInstance(); - case ShrinkAction.NAME: - return ShrinkActionTests.randomInstance(); - case FreezeAction.NAME: - return new FreezeAction(); - case WaitForSnapshotAction.NAME: - return WaitForSnapshotActionTests.randomInstance(); - case SetPriorityAction.NAME: - return SetPriorityActionTests.randomInstance(); - case SearchableSnapshotAction.NAME: - return SearchableSnapshotActionTests.randomInstance(); - case UnfollowAction.NAME: - return new UnfollowAction(); - case MigrateAction.NAME: - return new MigrateAction(randomBoolean()); - default: - throw new IllegalArgumentException("unsupported phase action [" + actionName + "]"); - } + return switch (actionName) { + case AllocateAction.NAME -> AllocateActionTests.randomInstance(); + case DeleteAction.NAME -> new DeleteAction(); + case ForceMergeAction.NAME -> ForceMergeActionTests.randomInstance(); + case ReadOnlyAction.NAME -> new ReadOnlyAction(); + case RolloverAction.NAME -> RolloverActionTests.randomInstance(); + case ShrinkAction.NAME -> ShrinkActionTests.randomInstance(); + case FreezeAction.NAME -> new FreezeAction(); + case WaitForSnapshotAction.NAME -> WaitForSnapshotActionTests.randomInstance(); + case SetPriorityAction.NAME -> SetPriorityActionTests.randomInstance(); + case SearchableSnapshotAction.NAME -> SearchableSnapshotActionTests.randomInstance(); + case UnfollowAction.NAME -> new UnfollowAction(); + case MigrateAction.NAME -> new MigrateAction(randomBoolean()); + default -> throw new IllegalArgumentException("unsupported phase action [" + actionName + "]"); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/ml/EvaluateDataFrameResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/ml/EvaluateDataFrameResponseTests.java index c4b52f46bc85f..902a3e95aa5c4 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/ml/EvaluateDataFrameResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/ml/EvaluateDataFrameResponseTests.java @@ -27,43 +27,40 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; +import java.util.Locale; import java.util.function.Predicate; public class EvaluateDataFrameResponseTests extends AbstractXContentTestCase { + private enum Evaluation { + OUTLIER_DETECTION, + CLASSIFICATION, + REGRESSION + } public static EvaluateDataFrameResponse randomResponse() { String evaluationName = randomFrom(OutlierDetection.NAME, Classification.NAME, Regression.NAME); - List metrics; - switch (evaluationName) { - case OutlierDetection.NAME: - metrics = randomSubsetOf( - Arrays.asList( - AucRocResultTests.randomResult(), - PrecisionMetricResultTests.randomResult(), - RecallMetricResultTests.randomResult(), - ConfusionMatrixMetricResultTests.randomResult() - ) - ); - break; - case Regression.NAME: - metrics = randomSubsetOf( - Arrays.asList(MeanSquaredErrorMetricResultTests.randomResult(), RSquaredMetricResultTests.randomResult()) - ); - break; - case Classification.NAME: - metrics = randomSubsetOf( - Arrays.asList( - AucRocResultTests.randomResult(), - AccuracyMetricResultTests.randomResult(), - org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetricResultTests.randomResult(), - org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetricResultTests.randomResult(), - MulticlassConfusionMatrixMetricResultTests.randomResult() - ) - ); - break; - default: - throw new AssertionError("Please add missing \"case\" variant to the \"switch\" statement"); - } + List metrics = switch (Evaluation.valueOf(evaluationName.toUpperCase(Locale.ROOT))) { + case OUTLIER_DETECTION -> randomSubsetOf( + Arrays.asList( + AucRocResultTests.randomResult(), + PrecisionMetricResultTests.randomResult(), + RecallMetricResultTests.randomResult(), + ConfusionMatrixMetricResultTests.randomResult() + ) + ); + case REGRESSION -> randomSubsetOf( + Arrays.asList(MeanSquaredErrorMetricResultTests.randomResult(), RSquaredMetricResultTests.randomResult()) + ); + case CLASSIFICATION -> randomSubsetOf( + Arrays.asList( + AucRocResultTests.randomResult(), + AccuracyMetricResultTests.randomResult(), + org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetricResultTests.randomResult(), + org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetricResultTests.randomResult(), + MulticlassConfusionMatrixMetricResultTests.randomResult() + ) + ); + }; return new EvaluateDataFrameResponse(evaluationName, metrics); } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfigTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfigTests.java index e8620f704da0d..ea72bc73c6754 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfigTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfigTests.java @@ -82,18 +82,14 @@ static DateHistogramGroupConfig randomDateHistogramGroupConfig() { final DateHistogramInterval delay = randomBoolean() ? new DateHistogramInterval(randomPositiveTimeValue()) : null; final String timezone = randomBoolean() ? randomZone().toString() : null; int i = randomIntBetween(0, 2); - final DateHistogramInterval interval; - switch (i) { - case 0: - interval = new DateHistogramInterval(randomPositiveTimeValue()); - return new DateHistogramGroupConfig.FixedInterval(field, interval, delay, timezone); - case 1: - interval = new DateHistogramInterval(randomTimeValue(1, 1, "m", "h", "d", "w")); - return new DateHistogramGroupConfig.CalendarInterval(field, interval, delay, timezone); - default: - interval = new DateHistogramInterval(randomPositiveTimeValue()); - return new DateHistogramGroupConfig(field, interval, delay, timezone); - } - + final DateHistogramInterval interval = switch (i) { + case 1 -> new DateHistogramInterval(randomTimeValue(1, 1, "m", "h", "d", "w")); + default -> new DateHistogramInterval(randomPositiveTimeValue()); + }; + return switch (i) { + case 0 -> new DateHistogramGroupConfig.FixedInterval(field, interval, delay, timezone); + case 1 -> new DateHistogramGroupConfig.CalendarInterval(field, interval, delay, timezone); + default -> new DateHistogramGroupConfig(field, interval, delay, timezone); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ClearServiceAccountTokenCacheRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ClearServiceAccountTokenCacheRequestTests.java index 308067ee9f7e2..5de54dec26ed8 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ClearServiceAccountTokenCacheRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ClearServiceAccountTokenCacheRequestTests.java @@ -48,28 +48,25 @@ public void testEqualsHashCode() { } private ClearServiceAccountTokenCacheRequest mutateInstance(ClearServiceAccountTokenCacheRequest request) { - switch (randomIntBetween(0, 2)) { - case 0: - return new ClearServiceAccountTokenCacheRequest( - randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getServiceName(), - request.getTokenNames() - ); - case 1: - return new ClearServiceAccountTokenCacheRequest( - request.getNamespace(), - randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getTokenNames() - ); - default: - return new ClearServiceAccountTokenCacheRequest( - request.getNamespace(), - request.getServiceName(), - randomValueOtherThanMany( - a -> Arrays.equals(a, request.getTokenNames()), - () -> randomArray(0, 3, String[]::new, () -> randomAlphaOfLengthBetween(3, 8)) - ) - ); - } + return switch (randomIntBetween(0, 2)) { + case 0 -> new ClearServiceAccountTokenCacheRequest( + randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getServiceName(), + request.getTokenNames() + ); + case 1 -> new ClearServiceAccountTokenCacheRequest( + request.getNamespace(), + randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getTokenNames() + ); + default -> new ClearServiceAccountTokenCacheRequest( + request.getNamespace(), + request.getServiceName(), + randomValueOtherThanMany( + a -> Arrays.equals(a, request.getTokenNames()), + () -> randomArray(0, 3, String[]::new, () -> randomAlphaOfLengthBetween(3, 8)) + ) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateApiKeyResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateApiKeyResponseTests.java index efa559a43bc6a..76d76dc01e98a 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateApiKeyResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateApiKeyResponseTests.java @@ -86,27 +86,22 @@ public void testEqualsHashCode() { } private static CreateApiKeyResponse mutateTestItem(CreateApiKeyResponse original) { - switch (randomIntBetween(0, 3)) { - case 0: - return new CreateApiKeyResponse(randomAlphaOfLength(7), original.getId(), original.getKey(), original.getExpiration()); - case 1: - return new CreateApiKeyResponse( - original.getName(), - randomAlphaOfLengthBetween(4, 8), - original.getKey(), - original.getExpiration() - ); - case 2: - return new CreateApiKeyResponse( - original.getName(), - original.getId(), - UUIDs.randomBase64UUIDSecureString(), - original.getExpiration() - ); - case 3: - return new CreateApiKeyResponse(original.getName(), original.getId(), original.getKey(), Instant.ofEpochMilli(150000)); - default: - return new CreateApiKeyResponse(randomAlphaOfLength(7), original.getId(), original.getKey(), original.getExpiration()); - } + return switch (randomIntBetween(0, 3)) { + case 0 -> new CreateApiKeyResponse(randomAlphaOfLength(7), original.getId(), original.getKey(), original.getExpiration()); + case 1 -> new CreateApiKeyResponse( + original.getName(), + randomAlphaOfLengthBetween(4, 8), + original.getKey(), + original.getExpiration() + ); + case 2 -> new CreateApiKeyResponse( + original.getName(), + original.getId(), + UUIDs.randomBase64UUIDSecureString(), + original.getExpiration() + ); + case 3 -> new CreateApiKeyResponse(original.getName(), original.getId(), original.getKey(), Instant.ofEpochMilli(150000)); + default -> new CreateApiKeyResponse(randomAlphaOfLength(7), original.getId(), original.getKey(), original.getExpiration()); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateServiceAccountTokenRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateServiceAccountTokenRequestTests.java index 6b2b04ea2a398..09d2846c3ae08 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateServiceAccountTokenRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/CreateServiceAccountTokenRequestTests.java @@ -66,35 +66,31 @@ public void testEqualsHashCode() { } private CreateServiceAccountTokenRequest mutateInstance(CreateServiceAccountTokenRequest request) { - switch (randomIntBetween(0, 3)) { - case 0: - return new CreateServiceAccountTokenRequest( - randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getServiceName(), - request.getTokenName(), - request.getRefreshPolicy() - ); - case 1: - return new CreateServiceAccountTokenRequest( - request.getNamespace(), - randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getTokenName(), - request.getRefreshPolicy() - ); - case 2: - return new CreateServiceAccountTokenRequest( - request.getNamespace(), - request.getServiceName(), - randomValueOtherThan(request.getTokenName(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getRefreshPolicy() - ); - default: - return new CreateServiceAccountTokenRequest( - request.getNamespace(), - request.getServiceName(), - request.getTokenName(), - randomValueOtherThan(request.getRefreshPolicy(), () -> randomFrom(RefreshPolicy.values())) - ); - } + return switch (randomIntBetween(0, 3)) { + case 0 -> new CreateServiceAccountTokenRequest( + randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getServiceName(), + request.getTokenName(), + request.getRefreshPolicy() + ); + case 1 -> new CreateServiceAccountTokenRequest( + request.getNamespace(), + randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getTokenName(), + request.getRefreshPolicy() + ); + case 2 -> new CreateServiceAccountTokenRequest( + request.getNamespace(), + request.getServiceName(), + randomValueOtherThan(request.getTokenName(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getRefreshPolicy() + ); + default -> new CreateServiceAccountTokenRequest( + request.getNamespace(), + request.getServiceName(), + request.getTokenName(), + randomValueOtherThan(request.getRefreshPolicy(), () -> randomFrom(RefreshPolicy.values())) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/DeleteServiceAccountTokenRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/DeleteServiceAccountTokenRequestTests.java index 8f5da59077c37..3f350bab1c670 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/DeleteServiceAccountTokenRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/DeleteServiceAccountTokenRequestTests.java @@ -65,36 +65,32 @@ public void testEqualsHashCode() { } private DeleteServiceAccountTokenRequest mutateInstance(DeleteServiceAccountTokenRequest request) { - switch (randomIntBetween(0, 3)) { - case 0: - return new DeleteServiceAccountTokenRequest( - randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getServiceName(), - request.getTokenName(), - request.getRefreshPolicy() - ); - case 1: - return new DeleteServiceAccountTokenRequest( - request.getNamespace(), - randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getTokenName(), - request.getRefreshPolicy() - ); - case 2: - return new DeleteServiceAccountTokenRequest( - request.getNamespace(), - request.getServiceName(), - randomValueOtherThan(request.getTokenName(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getRefreshPolicy() - ); - default: - return new DeleteServiceAccountTokenRequest( - request.getNamespace(), - request.getServiceName(), - request.getTokenName(), - randomValueOtherThan(request.getRefreshPolicy(), () -> randomFrom(RefreshPolicy.values())) - ); - } + return switch (randomIntBetween(0, 3)) { + case 0 -> new DeleteServiceAccountTokenRequest( + randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getServiceName(), + request.getTokenName(), + request.getRefreshPolicy() + ); + case 1 -> new DeleteServiceAccountTokenRequest( + request.getNamespace(), + randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getTokenName(), + request.getRefreshPolicy() + ); + case 2 -> new DeleteServiceAccountTokenRequest( + request.getNamespace(), + request.getServiceName(), + randomValueOtherThan(request.getTokenName(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getRefreshPolicy() + ); + default -> new DeleteServiceAccountTokenRequest( + request.getNamespace(), + request.getServiceName(), + request.getTokenName(), + randomValueOtherThan(request.getRefreshPolicy(), () -> randomFrom(RefreshPolicy.values())) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ExpressionRoleMappingTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ExpressionRoleMappingTests.java index 92a5762a2db1a..1c4d7012ec922 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ExpressionRoleMappingTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/ExpressionRoleMappingTests.java @@ -17,7 +17,6 @@ import java.io.IOException; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import static java.util.Collections.singletonList; @@ -79,71 +78,56 @@ public void testEqualsHashCode() { } private static ExpressionRoleMapping mutateTestItem(ExpressionRoleMapping original) throws IOException { - ExpressionRoleMapping mutated = null; - switch (randomIntBetween(0, 5)) { - case 0: - mutated = new ExpressionRoleMapping( - "namechanged", - FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), - singletonList("superuser"), - Collections.emptyList(), - null, - true - ); - break; - case 1: - mutated = new ExpressionRoleMapping( - "kerberosmapping", - FieldRoleMapperExpression.ofKeyValues("changed", "changed"), - singletonList("superuser"), - Collections.emptyList(), - null, - true - ); - break; - case 2: - mutated = new ExpressionRoleMapping( - "kerberosmapping", - FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), - singletonList("changed"), - Collections.emptyList(), - null, - true - ); - break; - case 3: - Map metadata = new HashMap<>(); - metadata.put("a", "b"); - mutated = new ExpressionRoleMapping( - "kerberosmapping", - FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), - singletonList("superuser"), - Collections.emptyList(), - metadata, - true - ); - break; - case 4: - mutated = new ExpressionRoleMapping( - "kerberosmapping", - FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), - Collections.emptyList(), - singletonList(new TemplateRoleName(Collections.singletonMap("source", "superuser"), TemplateRoleName.Format.STRING)), - null, - true - ); - break; - case 5: - mutated = new ExpressionRoleMapping( - "kerberosmapping", - FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), - singletonList("superuser"), - Collections.emptyList(), - null, - false - ); - break; - } - return mutated; + return switch (randomIntBetween(0, 5)) { + case 0 -> new ExpressionRoleMapping( + "namechanged", + FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), + singletonList("superuser"), + Collections.emptyList(), + null, + true + ); + case 1 -> new ExpressionRoleMapping( + "kerberosmapping", + FieldRoleMapperExpression.ofKeyValues("changed", "changed"), + singletonList("superuser"), + Collections.emptyList(), + null, + true + ); + case 2 -> new ExpressionRoleMapping( + "kerberosmapping", + FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), + singletonList("changed"), + Collections.emptyList(), + null, + true + ); + case 3 -> new ExpressionRoleMapping( + "kerberosmapping", + FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), + singletonList("superuser"), + Collections.emptyList(), + Map.of("a", "b"), + true + ); + case 4 -> new ExpressionRoleMapping( + "kerberosmapping", + FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), + Collections.emptyList(), + singletonList(new TemplateRoleName(Collections.singletonMap("source", "superuser"), TemplateRoleName.Format.STRING)), + null, + true + ); + case 5 -> new ExpressionRoleMapping( + "kerberosmapping", + FieldRoleMapperExpression.ofKeyValues("realm.name", "kerb1"), + singletonList("superuser"), + Collections.emptyList(), + null, + false + ); + default -> throw new UnsupportedOperationException(); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetApiKeyResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetApiKeyResponseTests.java index 9d1f3dd648740..f45f1dc9a894f 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetApiKeyResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetApiKeyResponseTests.java @@ -104,12 +104,10 @@ private static GetApiKeyResponse mutateTestItem(GetApiKeyResponse original) { "user-b", "realm-y" ); - switch (randomIntBetween(0, 2)) { - case 0: - return new GetApiKeyResponse(Arrays.asList(apiKeyInfo)); - default: - return new GetApiKeyResponse(Arrays.asList(apiKeyInfo)); - } + return switch (randomIntBetween(0, 2)) { + case 0 -> new GetApiKeyResponse(Arrays.asList(apiKeyInfo)); + default -> new GetApiKeyResponse(Arrays.asList(apiKeyInfo)); + }; } private static ApiKey createApiKeyInfo( diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetRoleMappingsResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetRoleMappingsResponseTests.java index 14394e3f2c6ad..b42eb5fa6fc0c 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetRoleMappingsResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetRoleMappingsResponseTests.java @@ -107,11 +107,10 @@ public void testEqualsHashCode() { } private static GetRoleMappingsResponse mutateTestItem(GetRoleMappingsResponse original) { - GetRoleMappingsResponse mutated = null; - switch (randomIntBetween(0, 1)) { - case 0: - final List roleMappingsList1 = new ArrayList<>(); - roleMappingsList1.add( + ExpressionRoleMapping originalRoleMapping = original.getMappings().get(0); + return switch (randomIntBetween(0, 1)) { + case 0 -> new GetRoleMappingsResponse( + List.of( new ExpressionRoleMapping( "ldapmapping", FieldRoleMapperExpression.ofGroups("cn=ipausers,cn=groups,cn=accounts,dc=ipademo,dc=local"), @@ -120,13 +119,10 @@ private static GetRoleMappingsResponse mutateTestItem(GetRoleMappingsResponse or null, false ) - ); - mutated = new GetRoleMappingsResponse(roleMappingsList1); - break; - case 1: - final List roleMappingsList2 = new ArrayList<>(); - ExpressionRoleMapping originalRoleMapping = original.getMappings().get(0); - roleMappingsList2.add( + ) + ); + default -> new GetRoleMappingsResponse( + List.of( new ExpressionRoleMapping( originalRoleMapping.getName(), FieldRoleMapperExpression.ofGroups("cn=ipausers,cn=groups,cn=accounts,dc=ipademo,dc=local"), @@ -135,10 +131,8 @@ private static GetRoleMappingsResponse mutateTestItem(GetRoleMappingsResponse or originalRoleMapping.getMetadata(), originalRoleMapping.isEnabled() == false ) - ); - mutated = new GetRoleMappingsResponse(roleMappingsList2); - break; - } - return mutated; + ) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountCredentialsRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountCredentialsRequestTests.java index 75a90519de502..07f34dd57040b 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountCredentialsRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountCredentialsRequestTests.java @@ -37,17 +37,15 @@ public void testEqualsHashCode() { } private GetServiceAccountCredentialsRequest mutateInstance(GetServiceAccountCredentialsRequest request) { - switch (randomIntBetween(0, 1)) { - case 0: - return new GetServiceAccountCredentialsRequest( - randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getServiceName() - ); - default: - return new GetServiceAccountCredentialsRequest( - request.getNamespace(), - randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)) - ); - } + return switch (randomIntBetween(0, 1)) { + case 0 -> new GetServiceAccountCredentialsRequest( + randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getServiceName() + ); + default -> new GetServiceAccountCredentialsRequest( + request.getNamespace(), + randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountsRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountsRequestTests.java index 63d49f35297c0..1fc9cb3042247 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountsRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GetServiceAccountsRequestTests.java @@ -54,17 +54,15 @@ public void testEqualsHashCode() { } private GetServiceAccountsRequest mutateInstance(GetServiceAccountsRequest request) { - switch (randomIntBetween(0, 1)) { - case 0: - return new GetServiceAccountsRequest( - randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), - request.getServiceName() - ); - default: - return new GetServiceAccountsRequest( - request.getNamespace(), - randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)) - ); - } + return switch (randomIntBetween(0, 1)) { + case 0 -> new GetServiceAccountsRequest( + randomValueOtherThan(request.getNamespace(), () -> randomAlphaOfLengthBetween(3, 8)), + request.getServiceName() + ); + default -> new GetServiceAccountsRequest( + request.getNamespace(), + randomValueOtherThan(request.getServiceName(), () -> randomAlphaOfLengthBetween(3, 8)) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GrantApiKeyRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GrantApiKeyRequestTests.java index 653b97a81418c..74968c9cef2fa 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GrantApiKeyRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/GrantApiKeyRequestTests.java @@ -96,14 +96,11 @@ public void testEqualsHashCode() { } private GrantApiKeyRequest.Grant clone(GrantApiKeyRequest.Grant grant) { - switch (grant.getGrantType()) { - case "password": - return GrantApiKeyRequest.Grant.passwordGrant(grant.getUsername(), grant.getPassword()); - case "access_token": - return GrantApiKeyRequest.Grant.accessTokenGrant(grant.getAccessToken()); - default: - throw new IllegalArgumentException("Cannot clone grant: " + Strings.toString(grant)); - } + return switch (grant.getGrantType()) { + case "password" -> GrantApiKeyRequest.Grant.passwordGrant(grant.getUsername(), grant.getPassword()); + case "access_token" -> GrantApiKeyRequest.Grant.accessTokenGrant(grant.getAccessToken()); + default -> throw new IllegalArgumentException("Cannot clone grant: " + Strings.toString(grant)); + }; } private CreateApiKeyRequest clone(CreateApiKeyRequest apiKeyRequest) { @@ -117,58 +114,53 @@ private CreateApiKeyRequest clone(CreateApiKeyRequest apiKeyRequest) { } private static GrantApiKeyRequest mutateTestItem(GrantApiKeyRequest original) { - switch (randomIntBetween(0, 3)) { - case 0: - return new GrantApiKeyRequest( - original.getGrant().getGrantType().equals("password") - ? GrantApiKeyRequest.Grant.accessTokenGrant(randomAlphaOfLength(24)) - : GrantApiKeyRequest.Grant.passwordGrant(randomAlphaOfLength(8), randomAlphaOfLengthBetween(6, 12).toCharArray()), - original.getApiKeyRequest() - ); - case 1: - return new GrantApiKeyRequest( - original.getGrant(), - new CreateApiKeyRequest( - randomAlphaOfLengthBetween(10, 15), - original.getApiKeyRequest().getRoles(), - original.getApiKeyRequest().getExpiration(), - original.getApiKeyRequest().getRefreshPolicy(), - original.getApiKeyRequest().getMetadata() - ) - ); - case 2: - return new GrantApiKeyRequest( - original.getGrant(), - new CreateApiKeyRequest( - original.getApiKeyRequest().getName(), - List.of(), // No role limits - original.getApiKeyRequest().getExpiration(), - original.getApiKeyRequest().getRefreshPolicy(), - original.getApiKeyRequest().getMetadata() - ) - ); - case 3: - return new GrantApiKeyRequest( - original.getGrant(), - new CreateApiKeyRequest( - original.getApiKeyRequest().getName(), - original.getApiKeyRequest().getRoles(), - original.getApiKeyRequest().getExpiration(), - original.getApiKeyRequest().getRefreshPolicy(), - randomValueOtherThan(original.getApiKeyRequest().getMetadata(), CreateApiKeyRequestTests::randomMetadata) - ) - ); - default: - return new GrantApiKeyRequest( - original.getGrant(), - new CreateApiKeyRequest( - original.getApiKeyRequest().getName(), - original.getApiKeyRequest().getRoles(), - TimeValue.timeValueMinutes(randomIntBetween(10, 120)), - original.getApiKeyRequest().getRefreshPolicy(), - original.getApiKeyRequest().getMetadata() - ) - ); - } + return switch (randomIntBetween(0, 3)) { + case 0 -> new GrantApiKeyRequest( + original.getGrant().getGrantType().equals("password") + ? GrantApiKeyRequest.Grant.accessTokenGrant(randomAlphaOfLength(24)) + : GrantApiKeyRequest.Grant.passwordGrant(randomAlphaOfLength(8), randomAlphaOfLengthBetween(6, 12).toCharArray()), + original.getApiKeyRequest() + ); + case 1 -> new GrantApiKeyRequest( + original.getGrant(), + new CreateApiKeyRequest( + randomAlphaOfLengthBetween(10, 15), + original.getApiKeyRequest().getRoles(), + original.getApiKeyRequest().getExpiration(), + original.getApiKeyRequest().getRefreshPolicy(), + original.getApiKeyRequest().getMetadata() + ) + ); + case 2 -> new GrantApiKeyRequest( + original.getGrant(), + new CreateApiKeyRequest( + original.getApiKeyRequest().getName(), + List.of(), // No role limits + original.getApiKeyRequest().getExpiration(), + original.getApiKeyRequest().getRefreshPolicy(), + original.getApiKeyRequest().getMetadata() + ) + ); + case 3 -> new GrantApiKeyRequest( + original.getGrant(), + new CreateApiKeyRequest( + original.getApiKeyRequest().getName(), + original.getApiKeyRequest().getRoles(), + original.getApiKeyRequest().getExpiration(), + original.getApiKeyRequest().getRefreshPolicy(), + randomValueOtherThan(original.getApiKeyRequest().getMetadata(), CreateApiKeyRequestTests::randomMetadata) + ) + ); + default -> new GrantApiKeyRequest( + original.getGrant(), + new CreateApiKeyRequest( + original.getApiKeyRequest().getName(), + original.getApiKeyRequest().getRoles(), + TimeValue.timeValueMinutes(randomIntBetween(10, 120)), + original.getApiKeyRequest().getRefreshPolicy(), + original.getApiKeyRequest().getMetadata() + ) + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateApiKeyResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateApiKeyResponseTests.java index 9834bd559da10..7532583b85125 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateApiKeyResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateApiKeyResponseTests.java @@ -114,27 +114,23 @@ public void testEqualsHashCode() { } private static InvalidateApiKeyResponse mutateTestItem(InvalidateApiKeyResponse original) { - switch (randomIntBetween(0, 2)) { - case 0: - return new InvalidateApiKeyResponse( - Arrays.asList(randomArray(2, 5, String[]::new, () -> randomAlphaOfLength(5))), - original.getPreviouslyInvalidatedApiKeys(), - original.getErrors() - ); - case 1: - return new InvalidateApiKeyResponse(original.getInvalidatedApiKeys(), Collections.emptyList(), original.getErrors()); - case 2: - return new InvalidateApiKeyResponse( - original.getInvalidatedApiKeys(), - original.getPreviouslyInvalidatedApiKeys(), - Collections.emptyList() - ); - default: - return new InvalidateApiKeyResponse( - Arrays.asList(randomArray(2, 5, String[]::new, () -> randomAlphaOfLength(5))), - original.getPreviouslyInvalidatedApiKeys(), - original.getErrors() - ); - } + return switch (randomIntBetween(0, 2)) { + case 0 -> new InvalidateApiKeyResponse( + Arrays.asList(randomArray(2, 5, String[]::new, () -> randomAlphaOfLength(5))), + original.getPreviouslyInvalidatedApiKeys(), + original.getErrors() + ); + case 1 -> new InvalidateApiKeyResponse(original.getInvalidatedApiKeys(), Collections.emptyList(), original.getErrors()); + case 2 -> new InvalidateApiKeyResponse( + original.getInvalidatedApiKeys(), + original.getPreviouslyInvalidatedApiKeys(), + Collections.emptyList() + ); + default -> new InvalidateApiKeyResponse( + Arrays.asList(randomArray(2, 5, String[]::new, () -> randomAlphaOfLength(5))), + original.getPreviouslyInvalidatedApiKeys(), + original.getErrors() + ); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateTokenRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateTokenRequestTests.java index cfe176af77ba9..2fadabba6c4b8 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateTokenRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/InvalidateTokenRequestTests.java @@ -72,18 +72,13 @@ public void testEqualsAndHashCode() { : InvalidateTokenRequest.refreshToken(token); final EqualsHashCodeTestUtils.MutateFunction mutate = r -> { int randomCase = randomIntBetween(1, 4); - switch (randomCase) { - case 1: - return InvalidateTokenRequest.refreshToken(randomAlphaOfLength(5)); - case 2: - return InvalidateTokenRequest.accessToken(randomAlphaOfLength(5)); - case 3: - return InvalidateTokenRequest.realmTokens(randomAlphaOfLength(5)); - case 4: - return InvalidateTokenRequest.userTokens(randomAlphaOfLength(5)); - default: - return new InvalidateTokenRequest(null, null, randomAlphaOfLength(5), randomAlphaOfLength(5)); - } + return switch (randomCase) { + case 1 -> InvalidateTokenRequest.refreshToken(randomAlphaOfLength(5)); + case 2 -> InvalidateTokenRequest.accessToken(randomAlphaOfLength(5)); + case 3 -> InvalidateTokenRequest.realmTokens(randomAlphaOfLength(5)); + case 4 -> InvalidateTokenRequest.userTokens(randomAlphaOfLength(5)); + default -> new InvalidateTokenRequest(null, null, randomAlphaOfLength(5), randomAlphaOfLength(5)); + }; }; EqualsHashCodeTestUtils.checkEqualsAndHashCode( request, diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/KibanaEnrollmentResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/KibanaEnrollmentResponseTests.java index caa90d32c3957..f09f04bf31eb6 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/KibanaEnrollmentResponseTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/KibanaEnrollmentResponseTests.java @@ -63,29 +63,25 @@ public void testEqualsHashCode() { } private static KibanaEnrollmentResponse mutateTestItem(KibanaEnrollmentResponse original) { - switch (randomIntBetween(0, 3)) { - case 0: - return new KibanaEnrollmentResponse( - randomAlphaOfLengthBetween(14, 20), - new SecureString(randomAlphaOfLengthBetween(71, 90).toCharArray()), - randomAlphaOfLength(52) - ); - case 1: - return new KibanaEnrollmentResponse( - original.getTokenName(), - new SecureString(randomAlphaOfLengthBetween(71, 90).toCharArray()), - randomAlphaOfLength(52) - ); - case 2: - return new KibanaEnrollmentResponse(randomAlphaOfLengthBetween(14, 20), original.getTokenValue(), randomAlphaOfLength(52)); - case 3: - return new KibanaEnrollmentResponse( - randomAlphaOfLengthBetween(14, 20), - new SecureString(randomAlphaOfLengthBetween(71, 90).toCharArray()), - original.getHttpCa() - ); - } - // we never reach here - return null; + return switch (randomIntBetween(0, 3)) { + case 0 -> new KibanaEnrollmentResponse( + randomAlphaOfLengthBetween(14, 20), + new SecureString(randomAlphaOfLengthBetween(71, 90).toCharArray()), + randomAlphaOfLength(52) + ); + case 1 -> new KibanaEnrollmentResponse( + original.getTokenName(), + new SecureString(randomAlphaOfLengthBetween(71, 90).toCharArray()), + randomAlphaOfLength(52) + ); + case 2 -> new KibanaEnrollmentResponse(randomAlphaOfLengthBetween(14, 20), original.getTokenValue(), randomAlphaOfLength(52)); + case 3 -> new KibanaEnrollmentResponse( + randomAlphaOfLengthBetween(14, 20), + new SecureString(randomAlphaOfLengthBetween(71, 90).toCharArray()), + original.getHttpCa() + ); + // we never reach here + default -> null; + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/QueryApiKeyRequestTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/QueryApiKeyRequestTests.java index f786902d3eb2b..dc6306b1a90d8 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/QueryApiKeyRequestTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/QueryApiKeyRequestTests.java @@ -78,74 +78,61 @@ public void testValidation() { } private QueryApiKeyRequest mutateInstance(QueryApiKeyRequest request) { - switch (randomIntBetween(0, 5)) { - case 0: - return new QueryApiKeyRequest( - randomValueOtherThan(request.getQueryBuilder(), QueryApiKeyRequestTests::randomQueryBuilder), - request.getFrom(), - request.getSize(), - request.getFieldSortBuilders(), - request.getSearchAfterBuilder() - ); - case 1: - return new QueryApiKeyRequest( - request.getQueryBuilder(), - request.getFrom() + 1, - request.getSize(), - request.getFieldSortBuilders(), - request.getSearchAfterBuilder() - ); - case 2: - return new QueryApiKeyRequest( - request.getQueryBuilder(), - request.getFrom(), - request.getSize() + 1, - request.getFieldSortBuilders(), - request.getSearchAfterBuilder() - ); - case 3: - return new QueryApiKeyRequest( - request.getQueryBuilder(), - request.getFrom(), - request.getSize(), - randomValueOtherThan(request.getFieldSortBuilders(), QueryApiKeyRequestTests::randomFieldSortBuilders), - request.getSearchAfterBuilder() - ); - default: - return new QueryApiKeyRequest( - request.getQueryBuilder(), - request.getFrom(), - request.getSize(), - request.getFieldSortBuilders(), - randomValueOtherThan(request.getSearchAfterBuilder(), QueryApiKeyRequestTests::randomSearchAfterBuilder) - ); - - } + return switch (randomIntBetween(0, 5)) { + case 0 -> new QueryApiKeyRequest( + randomValueOtherThan(request.getQueryBuilder(), QueryApiKeyRequestTests::randomQueryBuilder), + request.getFrom(), + request.getSize(), + request.getFieldSortBuilders(), + request.getSearchAfterBuilder() + ); + case 1 -> new QueryApiKeyRequest( + request.getQueryBuilder(), + request.getFrom() + 1, + request.getSize(), + request.getFieldSortBuilders(), + request.getSearchAfterBuilder() + ); + case 2 -> new QueryApiKeyRequest( + request.getQueryBuilder(), + request.getFrom(), + request.getSize() + 1, + request.getFieldSortBuilders(), + request.getSearchAfterBuilder() + ); + case 3 -> new QueryApiKeyRequest( + request.getQueryBuilder(), + request.getFrom(), + request.getSize(), + randomValueOtherThan(request.getFieldSortBuilders(), QueryApiKeyRequestTests::randomFieldSortBuilders), + request.getSearchAfterBuilder() + ); + default -> new QueryApiKeyRequest( + request.getQueryBuilder(), + request.getFrom(), + request.getSize(), + request.getFieldSortBuilders(), + randomValueOtherThan(request.getSearchAfterBuilder(), QueryApiKeyRequestTests::randomSearchAfterBuilder) + ); + }; } public static QueryBuilder randomQueryBuilder() { - switch (randomIntBetween(0, 5)) { - case 0: - return QueryBuilders.matchAllQuery(); - case 1: - return QueryBuilders.termQuery( - randomAlphaOfLengthBetween(3, 8), - randomFrom(randomAlphaOfLength(8), randomInt(), randomLong(), randomDouble(), randomFloat()) - ); - case 2: - return QueryBuilders.idsQuery().addIds(randomArray(1, 5, String[]::new, () -> randomAlphaOfLength(20))); - case 3: - return QueryBuilders.prefixQuery(randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); - case 4: - return QueryBuilders.wildcardQuery( - randomAlphaOfLengthBetween(3, 8), - randomAlphaOfLengthBetween(0, 3) + "*" + randomAlphaOfLengthBetween(0, 3) - ); - case 5: - return QueryBuilders.rangeQuery(randomAlphaOfLengthBetween(3, 8)).from(randomNonNegativeLong()).to(randomNonNegativeLong()); - default: - return null; - } + return switch (randomIntBetween(0, 5)) { + case 0 -> QueryBuilders.matchAllQuery(); + case 1 -> QueryBuilders.termQuery( + randomAlphaOfLengthBetween(3, 8), + randomFrom(randomAlphaOfLength(8), randomInt(), randomLong(), randomDouble(), randomFloat()) + ); + case 2 -> QueryBuilders.idsQuery().addIds(randomArray(1, 5, String[]::new, () -> randomAlphaOfLength(20))); + case 3 -> QueryBuilders.prefixQuery(randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); + case 4 -> QueryBuilders.wildcardQuery( + randomAlphaOfLengthBetween(3, 8), + randomAlphaOfLengthBetween(0, 3) + "*" + randomAlphaOfLengthBetween(0, 3) + ); + case 5 -> QueryBuilders.rangeQuery(randomAlphaOfLengthBetween(3, 8)).from(randomNonNegativeLong()).to(randomNonNegativeLong()); + default -> null; + }; } public static List randomFieldSortBuilders() { diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/GlobalOperationPrivilegeTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/GlobalOperationPrivilegeTests.java index 5a6f05ebad062..0e034aba4d581 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/GlobalOperationPrivilegeTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/security/user/privileges/GlobalOperationPrivilegeTests.java @@ -61,19 +61,15 @@ public void testEqualsHashCode() { } private static GlobalOperationPrivilege mutateTestItem(GlobalOperationPrivilege original) { - switch (randomIntBetween(0, 2)) { - case 0: - return new GlobalOperationPrivilege(randomAlphaOfLength(5), original.getOperation(), original.getRaw()); - case 1: - return new GlobalOperationPrivilege(original.getCategory(), randomAlphaOfLength(5), original.getRaw()); - case 2: - return new GlobalOperationPrivilege( - original.getCategory(), - original.getOperation(), - Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4)) - ); - default: - return new GlobalOperationPrivilege(randomAlphaOfLength(5), original.getOperation(), original.getRaw()); - } + return switch (randomIntBetween(0, 2)) { + case 0 -> new GlobalOperationPrivilege(randomAlphaOfLength(5), original.getOperation(), original.getRaw()); + case 1 -> new GlobalOperationPrivilege(original.getCategory(), randomAlphaOfLength(5), original.getRaw()); + case 2 -> new GlobalOperationPrivilege( + original.getCategory(), + original.getOperation(), + Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4)) + ); + default -> new GlobalOperationPrivilege(randomAlphaOfLength(5), original.getOperation(), original.getRaw()); + }; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/TransformConfigTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/TransformConfigTests.java index bf01b876f5252..1b6c457e45d82 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/TransformConfigTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/TransformConfigTests.java @@ -72,23 +72,13 @@ public static RetentionPolicyConfig randomRetentionPolicyConfig() { public static Map randomMetadata() { return randomMap(0, 10, () -> { String key = randomAlphaOfLengthBetween(1, 10); - Object value; - switch (randomIntBetween(0, 3)) { - case 0: - value = null; - break; - case 1: - value = randomLong(); - break; - case 2: - value = randomAlphaOfLengthBetween(1, 10); - break; - case 3: - value = randomMap(0, 10, () -> Tuple.tuple(randomAlphaOfLengthBetween(1, 10), randomAlphaOfLengthBetween(1, 10))); - break; - default: - throw new AssertionError(); - } + Object value = switch (randomIntBetween(0, 3)) { + case 0 -> null; + case 1 -> randomLong(); + case 2 -> randomAlphaOfLengthBetween(1, 10); + case 3 -> randomMap(0, 10, () -> Tuple.tuple(randomAlphaOfLengthBetween(1, 10), randomAlphaOfLengthBetween(1, 10))); + default -> throw new AssertionError(); + }; return Tuple.tuple(key, value); }); } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/AggregationConfigTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/AggregationConfigTests.java index 2d24b422bac68..77d65a7f0f969 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/AggregationConfigTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/AggregationConfigTests.java @@ -61,17 +61,13 @@ protected NamedXContentRegistry xContentRegistry() { private static AggregationBuilder getRandomSupportedAggregation() { final int numberOfSupportedAggs = 4; - switch (randomIntBetween(1, numberOfSupportedAggs)) { - case 1: - return AggregationBuilders.avg(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); - case 2: - return AggregationBuilders.min(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); - case 3: - return AggregationBuilders.max(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); - case 4: - return AggregationBuilders.sum(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); - } + return switch (randomIntBetween(1, numberOfSupportedAggs)) { + case 1 -> AggregationBuilders.avg(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); + case 2 -> AggregationBuilders.min(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); + case 3 -> AggregationBuilders.max(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); + case 4 -> AggregationBuilders.sum(randomAlphaOfLengthBetween(1, 10)).field(randomAlphaOfLengthBetween(1, 10)); + default -> null; + }; - return null; } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfigTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfigTests.java index 564c8725841ce..1e5532dd907e6 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfigTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/transform/transforms/pivot/GroupConfigTests.java @@ -34,24 +34,13 @@ public static GroupConfig randomGroupConfig() { for (int i = 0; i < randomIntBetween(1, 4); ++i) { String targetFieldName = randomAlphaOfLengthBetween(1, 20); if (names.add(targetFieldName)) { - SingleGroupSource groupBy = null; SingleGroupSource.Type type = randomFrom(SingleGroupSource.Type.values()); - switch (type) { - case TERMS: - groupBy = TermsGroupSourceTests.randomTermsGroupSource(); - break; - case HISTOGRAM: - groupBy = HistogramGroupSourceTests.randomHistogramGroupSource(); - break; - case DATE_HISTOGRAM: - groupBy = DateHistogramGroupSourceTests.randomDateHistogramGroupSource(); - break; - case GEOTILE_GRID: - groupBy = GeoTileGroupSourceTests.randomGeoTileGroupSource(); - break; - default: - fail("unknown group source type, please implement tests and add support here"); - } + SingleGroupSource groupBy = switch (type) { + case TERMS -> TermsGroupSourceTests.randomTermsGroupSource(); + case HISTOGRAM -> HistogramGroupSourceTests.randomHistogramGroupSource(); + case DATE_HISTOGRAM -> DateHistogramGroupSourceTests.randomDateHistogramGroupSource(); + case GEOTILE_GRID -> GeoTileGroupSourceTests.randomGeoTileGroupSource(); + }; groups.put(targetFieldName, groupBy); } } diff --git a/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/InstallPluginAction.java b/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/InstallPluginAction.java index 75eedf4a6b84c..02e25ac865b41 100644 --- a/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/InstallPluginAction.java +++ b/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/InstallPluginAction.java @@ -264,15 +264,12 @@ Build.Flavor buildFlavor() { private static void handleInstallXPack(final Build.Flavor flavor) throws UserException { switch (flavor) { - case DEFAULT: - throw new UserException(ExitCodes.CONFIG, "this distribution of Elasticsearch contains X-Pack by default"); - case OSS: - throw new UserException( - ExitCodes.CONFIG, - "X-Pack is not available with the oss distribution; to use X-Pack features use the default distribution" - ); - case UNKNOWN: - throw new IllegalStateException("your distribution is broken"); + case DEFAULT -> throw new UserException(ExitCodes.CONFIG, "this distribution of Elasticsearch contains X-Pack by default"); + case OSS -> throw new UserException( + ExitCodes.CONFIG, + "X-Pack is not available with the oss distribution; to use X-Pack features use the default distribution" + ); + case UNKNOWN -> throw new IllegalStateException("your distribution is broken"); } } diff --git a/libs/core/src/main/java/org/elasticsearch/core/Booleans.java b/libs/core/src/main/java/org/elasticsearch/core/Booleans.java index a7201761f44a0..062c613de5dc4 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/Booleans.java +++ b/libs/core/src/main/java/org/elasticsearch/core/Booleans.java @@ -118,16 +118,10 @@ public static boolean parseBooleanLenient(String value, boolean defaultValue) { if (value == null) { return defaultValue; } - switch (value) { - case "false": - case "0": - case "off": - case "no": - return false; - - default: - return true; - } + return switch (value) { + case "false", "0", "off", "no" -> false; + default -> true; + }; } /** diff --git a/libs/core/src/main/java/org/elasticsearch/core/TimeValue.java b/libs/core/src/main/java/org/elasticsearch/core/TimeValue.java index b74fe01e43821..2b178efe2cd0f 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/TimeValue.java +++ b/libs/core/src/main/java/org/elasticsearch/core/TimeValue.java @@ -318,24 +318,15 @@ public String getStringRep() { if (duration < 0) { return Long.toString(duration); } - switch (timeUnit) { - case NANOSECONDS: - return duration + "nanos"; - case MICROSECONDS: - return duration + "micros"; - case MILLISECONDS: - return duration + "ms"; - case SECONDS: - return duration + "s"; - case MINUTES: - return duration + "m"; - case HOURS: - return duration + "h"; - case DAYS: - return duration + "d"; - default: - throw new IllegalArgumentException("unknown time unit: " + timeUnit.name()); - } + return switch (timeUnit) { + case NANOSECONDS -> duration + "nanos"; + case MICROSECONDS -> duration + "micros"; + case MILLISECONDS -> duration + "ms"; + case SECONDS -> duration + "s"; + case MINUTES -> duration + "m"; + case HOURS -> duration + "h"; + case DAYS -> duration + "d"; + }; } public static TimeValue parseTimeValue(String sValue, String settingName) { diff --git a/libs/dissect/src/main/java/org/elasticsearch/dissect/DissectMatch.java b/libs/dissect/src/main/java/org/elasticsearch/dissect/DissectMatch.java index 83a4fc23d9be8..5714870ab8520 100644 --- a/libs/dissect/src/main/java/org/elasticsearch/dissect/DissectMatch.java +++ b/libs/dissect/src/main/java/org/elasticsearch/dissect/DissectMatch.java @@ -60,22 +60,13 @@ void add(DissectKey key, String value) { return; } switch (key.getModifier()) { - case NONE: - simpleResults.put(key.getName(), value); - break; - case APPEND: - appendResults.computeIfAbsent(key.getName(), k -> new AppendResult(appendSeparator)).addValue(value, implicitAppendOrder++); - break; - case APPEND_WITH_ORDER: - appendResults.computeIfAbsent(key.getName(), k -> new AppendResult(appendSeparator)) - .addValue(value, key.getAppendPosition()); - break; - case FIELD_NAME: - referenceResults.computeIfAbsent(key.getName(), k -> new ReferenceResult()).setKey(value); - break; - case FIELD_VALUE: - referenceResults.computeIfAbsent(key.getName(), k -> new ReferenceResult()).setValue(value); - break; + case NONE -> simpleResults.put(key.getName(), value); + case APPEND -> appendResults.computeIfAbsent(key.getName(), k -> new AppendResult(appendSeparator)) + .addValue(value, implicitAppendOrder++); + case APPEND_WITH_ORDER -> appendResults.computeIfAbsent(key.getName(), k -> new AppendResult(appendSeparator)) + .addValue(value, key.getAppendPosition()); + case FIELD_NAME -> referenceResults.computeIfAbsent(key.getName(), k -> new ReferenceResult()).setKey(value); + case FIELD_VALUE -> referenceResults.computeIfAbsent(key.getName(), k -> new ReferenceResult()).setValue(value); } } diff --git a/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java b/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java index 3e1aabeb4063d..da7386d6bb00f 100644 --- a/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java +++ b/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java @@ -506,17 +506,13 @@ private static double nextNumber(StreamTokenizer stream) throws IOException, Par } private static String tokenString(StreamTokenizer stream) { - switch (stream.ttype) { - case StreamTokenizer.TT_WORD: - return stream.sval; - case StreamTokenizer.TT_EOF: - return EOF; - case StreamTokenizer.TT_EOL: - return EOL; - case StreamTokenizer.TT_NUMBER: - return NUMBER; - } - return "'" + (char) stream.ttype + "'"; + return switch (stream.ttype) { + case StreamTokenizer.TT_WORD -> stream.sval; + case StreamTokenizer.TT_EOF -> EOF; + case StreamTokenizer.TT_EOL -> EOL; + case StreamTokenizer.TT_NUMBER -> NUMBER; + default -> "'" + (char) stream.ttype + "'"; + }; } private static boolean isNumberNext(StreamTokenizer stream) throws IOException { diff --git a/libs/grok/src/main/java/org/elasticsearch/grok/GrokCaptureType.java b/libs/grok/src/main/java/org/elasticsearch/grok/GrokCaptureType.java index 23a71b72ee212..d301febb261ef 100644 --- a/libs/grok/src/main/java/org/elasticsearch/grok/GrokCaptureType.java +++ b/libs/grok/src/main/java/org/elasticsearch/grok/GrokCaptureType.java @@ -58,22 +58,15 @@ T nativeExtracter(int[] backRefs, NativeExtracterMap map) { abstract T nativeExtracter(int[] backRefs, NativeExtracterMap map); static GrokCaptureType fromString(String str) { - switch (str) { - case "string": - return STRING; - case "int": - return INTEGER; - case "long": - return LONG; - case "float": - return FLOAT; - case "double": - return DOUBLE; - case "boolean": - return BOOLEAN; - default: - return STRING; - } + return switch (str) { + case "string" -> STRING; + case "int" -> INTEGER; + case "long" -> LONG; + case "float" -> FLOAT; + case "double" -> DOUBLE; + case "boolean" -> BOOLEAN; + default -> STRING; + }; } protected final GrokCaptureExtracter rawExtracter(int[] backRefs, Consumer emit) { diff --git a/libs/lz4/src/main/java/org/elasticsearch/lz4/LZ4SafeUtils.java b/libs/lz4/src/main/java/org/elasticsearch/lz4/LZ4SafeUtils.java index f615f4040c3aa..f97af10bd7623 100644 --- a/libs/lz4/src/main/java/org/elasticsearch/lz4/LZ4SafeUtils.java +++ b/libs/lz4/src/main/java/org/elasticsearch/lz4/LZ4SafeUtils.java @@ -74,27 +74,15 @@ static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCo int dec = 0; assert dOff >= matchOff && dOff - matchOff < 8; switch (dOff - matchOff) { - case 1: - matchOff -= 3; - break; - case 2: - matchOff -= 2; - break; - case 3: + case 1 -> matchOff -= 3; + case 2 -> matchOff -= 2; + case 3 -> { matchOff -= 3; dec = -1; - break; - case 5: - dec = 1; - break; - case 6: - dec = 2; - break; - case 7: - dec = 3; - break; - default: - break; + } + case 5 -> dec = 1; + case 6 -> dec = 2; + case 7 -> dec = 3; } copy4Bytes(dest, matchOff, dest, dOff); diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DerParser.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DerParser.java index be9357255bb7f..f0b6d737c713b 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DerParser.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DerParser.java @@ -268,17 +268,15 @@ public String getOid() throws IOException { } StringBuilder sb = new StringBuilder(64); switch (value[0] / 40) { - case 0: - sb.append('0'); - break; - case 1: + case 0 -> sb.append('0'); + case 1 -> { sb.append('1'); value[0] -= 40; - break; - default: + } + default -> { sb.append('2'); value[0] -= 80; - break; + } } int oidPart = 0; for (int i = 0; i < length; i++) { diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java index 7fa3132b028c7..25545572b5e9a 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java @@ -654,17 +654,14 @@ private static String getKeyAlgorithmIdentifier(byte[] keyBytes) throws IOExcept DerParser.Asn1Object algSequence = parser.readAsn1Object(); parser = algSequence.getParser(); String oidString = parser.readAsn1Object().getOid(); - switch (oidString) { - case "1.2.840.10040.4.1": - return "DSA"; - case "1.2.840.113549.1.1.1": - return "RSA"; - case "1.2.840.10045.2.1": - return "EC"; - } - throw new GeneralSecurityException( - "Error parsing key algorithm identifier. Algorithm with OID [" + oidString + "] is not supported" - ); + return switch (oidString) { + case "1.2.840.10040.4.1" -> "DSA"; + case "1.2.840.113549.1.1.1" -> "RSA"; + case "1.2.840.10045.2.1" -> "EC"; + default -> throw new GeneralSecurityException( + "Error parsing key algorithm identifier. Algorithm with OID [" + oidString + "] is not supported" + ); + }; } public static List readCertificates(Collection certPaths) throws CertificateException, IOException { @@ -683,92 +680,55 @@ public static List readCertificates(Collection certPaths) thr } private static String getAlgorithmNameFromOid(String oidString) throws GeneralSecurityException { - switch (oidString) { - case "1.2.840.10040.4.1": - return "DSA"; - case "1.2.840.113549.1.1.1": - return "RSA"; - case "1.2.840.10045.2.1": - return "EC"; - case "1.3.14.3.2.7": - return "DES-CBC"; - case "2.16.840.1.101.3.4.1.1": - return "AES-128_ECB"; - case "2.16.840.1.101.3.4.1.2": - return "AES-128_CBC"; - case "2.16.840.1.101.3.4.1.3": - return "AES-128_OFB"; - case "2.16.840.1.101.3.4.1.4": - return "AES-128_CFB"; - case "2.16.840.1.101.3.4.1.6": - return "AES-128_GCM"; - case "2.16.840.1.101.3.4.1.21": - return "AES-192_ECB"; - case "2.16.840.1.101.3.4.1.22": - return "AES-192_CBC"; - case "2.16.840.1.101.3.4.1.23": - return "AES-192_OFB"; - case "2.16.840.1.101.3.4.1.24": - return "AES-192_CFB"; - case "2.16.840.1.101.3.4.1.26": - return "AES-192_GCM"; - case "2.16.840.1.101.3.4.1.41": - return "AES-256_ECB"; - case "2.16.840.1.101.3.4.1.42": - return "AES-256_CBC"; - case "2.16.840.1.101.3.4.1.43": - return "AES-256_OFB"; - case "2.16.840.1.101.3.4.1.44": - return "AES-256_CFB"; - case "2.16.840.1.101.3.4.1.46": - return "AES-256_GCM"; - case "2.16.840.1.101.3.4.1.5": - return "AESWrap-128"; - case "2.16.840.1.101.3.4.1.25": - return "AESWrap-192"; - case "2.16.840.1.101.3.4.1.45": - return "AESWrap-256"; - } - return null; + return switch (oidString) { + case "1.2.840.10040.4.1" -> "DSA"; + case "1.2.840.113549.1.1.1" -> "RSA"; + case "1.2.840.10045.2.1" -> "EC"; + case "1.3.14.3.2.7" -> "DES-CBC"; + case "2.16.840.1.101.3.4.1.1" -> "AES-128_ECB"; + case "2.16.840.1.101.3.4.1.2" -> "AES-128_CBC"; + case "2.16.840.1.101.3.4.1.3" -> "AES-128_OFB"; + case "2.16.840.1.101.3.4.1.4" -> "AES-128_CFB"; + case "2.16.840.1.101.3.4.1.6" -> "AES-128_GCM"; + case "2.16.840.1.101.3.4.1.21" -> "AES-192_ECB"; + case "2.16.840.1.101.3.4.1.22" -> "AES-192_CBC"; + case "2.16.840.1.101.3.4.1.23" -> "AES-192_OFB"; + case "2.16.840.1.101.3.4.1.24" -> "AES-192_CFB"; + case "2.16.840.1.101.3.4.1.26" -> "AES-192_GCM"; + case "2.16.840.1.101.3.4.1.41" -> "AES-256_ECB"; + case "2.16.840.1.101.3.4.1.42" -> "AES-256_CBC"; + case "2.16.840.1.101.3.4.1.43" -> "AES-256_OFB"; + case "2.16.840.1.101.3.4.1.44" -> "AES-256_CFB"; + case "2.16.840.1.101.3.4.1.46" -> "AES-256_GCM"; + case "2.16.840.1.101.3.4.1.5" -> "AESWrap-128"; + case "2.16.840.1.101.3.4.1.25" -> "AESWrap-192"; + case "2.16.840.1.101.3.4.1.45" -> "AESWrap-256"; + default -> null; + }; } private static String getEcCurveNameFromOid(String oidString) throws GeneralSecurityException { - switch (oidString) { + return switch (oidString) { // see https://tools.ietf.org/html/rfc5480#section-2.1.1.1 - case "1.2.840.10045.3.1": - return "secp192r1"; - case "1.3.132.0.1": - return "sect163k1"; - case "1.3.132.0.15": - return "sect163r2"; - case "1.3.132.0.33": - return "secp224r1"; - case "1.3.132.0.26": - return "sect233k1"; - case "1.3.132.0.27": - return "sect233r1"; - case "1.2.840.10045.3.1.7": - return "secp256r1"; - case "1.3.132.0.16": - return "sect283k1"; - case "1.3.132.0.17": - return "sect283r1"; - case "1.3.132.0.34": - return "secp384r1"; - case "1.3.132.0.36": - return "sect409k1"; - case "1.3.132.0.37": - return "sect409r1"; - case "1.3.132.0.35": - return "secp521r1"; - case "1.3.132.0.38": - return "sect571k1"; - case "1.3.132.0.39": - return "sect571r1"; - } - throw new GeneralSecurityException( - "Error parsing EC named curve identifier. Named curve with OID: " + oidString + " is not supported" - ); + case "1.2.840.10045.3.1" -> "secp192r1"; + case "1.3.132.0.1" -> "sect163k1"; + case "1.3.132.0.15" -> "sect163r2"; + case "1.3.132.0.33" -> "secp224r1"; + case "1.3.132.0.26" -> "sect233k1"; + case "1.3.132.0.27" -> "sect233r1"; + case "1.2.840.10045.3.1.7" -> "secp256r1"; + case "1.3.132.0.16" -> "sect283k1"; + case "1.3.132.0.17" -> "sect283r1"; + case "1.3.132.0.34" -> "secp384r1"; + case "1.3.132.0.36" -> "sect409k1"; + case "1.3.132.0.37" -> "sect409r1"; + case "1.3.132.0.35" -> "secp521r1"; + case "1.3.132.0.38" -> "sect571k1"; + case "1.3.132.0.39" -> "sect571r1"; + default -> throw new GeneralSecurityException( + "Error parsing EC named curve identifier. Named curve with OID: " + oidString + " is not supported" + ); + }; } } diff --git a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java index 3eaba0af8810a..55aae27d659fc 100644 --- a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java +++ b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java @@ -91,54 +91,51 @@ public void testEqualsAndHashCode() { orig.getCipherSuites(), orig.getSupportedProtocols() ), - orig -> { - switch (randomIntBetween(1, 4)) { - case 1: - return new SslConfiguration( - true, - orig.getTrustConfig(), - orig.getKeyConfig(), - randomValueOtherThan(orig.getVerificationMode(), () -> randomFrom(SslVerificationMode.values())), - orig.getClientAuth(), - orig.getCipherSuites(), - orig.getSupportedProtocols() - ); - case 2: - return new SslConfiguration( - true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - randomValueOtherThan(orig.getClientAuth(), () -> randomFrom(SslClientAuthenticationMode.values())), - orig.getCipherSuites(), - orig.getSupportedProtocols() - ); - case 3: - return new SslConfiguration( - true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - orig.getClientAuth(), - DEFAULT_CIPHERS, - orig.getSupportedProtocols() - ); - case 4: - default: - return new SslConfiguration( - true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - orig.getClientAuth(), - orig.getCipherSuites(), - Arrays.asList(VALID_PROTOCOLS) - ); - } - } + this::mutateSslConfiguration ); } + private SslConfiguration mutateSslConfiguration(SslConfiguration orig) { + return switch (randomIntBetween(1, 4)) { + case 1 -> new SslConfiguration( + true, + orig.getTrustConfig(), + orig.getKeyConfig(), + randomValueOtherThan(orig.getVerificationMode(), () -> randomFrom(SslVerificationMode.values())), + orig.getClientAuth(), + orig.getCipherSuites(), + orig.getSupportedProtocols() + ); + case 2 -> new SslConfiguration( + true, + orig.getTrustConfig(), + orig.getKeyConfig(), + orig.getVerificationMode(), + randomValueOtherThan(orig.getClientAuth(), () -> randomFrom(SslClientAuthenticationMode.values())), + orig.getCipherSuites(), + orig.getSupportedProtocols() + ); + case 3 -> new SslConfiguration( + true, + orig.getTrustConfig(), + orig.getKeyConfig(), + orig.getVerificationMode(), + orig.getClientAuth(), + DEFAULT_CIPHERS, + orig.getSupportedProtocols() + ); + default -> new SslConfiguration( + true, + orig.getTrustConfig(), + orig.getKeyConfig(), + orig.getVerificationMode(), + orig.getClientAuth(), + orig.getCipherSuites(), + Arrays.asList(VALID_PROTOCOLS) + ); + }; + } + public void testDependentFiles() { final SslTrustConfig trustConfig = Mockito.mock(SslTrustConfig.class); final SslKeyConfig keyConfig = Mockito.mock(SslKeyConfig.class); diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java index fa5ce84155065..e9ca43248b480 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java @@ -121,29 +121,16 @@ private static UnknownFieldParser consumeUnknow return (objectParser, field, location, parser, value, context) -> { XContentParser.Token t = parser.currentToken(); switch (t) { - case VALUE_STRING: - consumer.accept(value, field, parser.text()); - break; - case VALUE_NUMBER: - consumer.accept(value, field, parser.numberValue()); - break; - case VALUE_BOOLEAN: - consumer.accept(value, field, parser.booleanValue()); - break; - case VALUE_NULL: - consumer.accept(value, field, null); - break; - case START_OBJECT: - consumer.accept(value, field, parser.map()); - break; - case START_ARRAY: - consumer.accept(value, field, parser.list()); - break; - default: - throw new XContentParseException( - parser.getTokenLocation(), - "[" + objectParser.name + "] cannot parse field [" + field + "] with value type [" + t + "]" - ); + case VALUE_STRING -> consumer.accept(value, field, parser.text()); + case VALUE_NUMBER -> consumer.accept(value, field, parser.numberValue()); + case VALUE_BOOLEAN -> consumer.accept(value, field, parser.booleanValue()); + case VALUE_NULL -> consumer.accept(value, field, null); + case START_OBJECT -> consumer.accept(value, field, parser.map()); + case START_ARRAY -> consumer.accept(value, field, parser.list()); + default -> throw new XContentParseException( + parser.getTokenLocation(), + "[" + objectParser.name + "] cannot parse field [" + field + "] with value type [" + t + "]" + ); } }; } @@ -642,7 +629,7 @@ private void throwFailedToParse(XContentParser parser, String currentFieldName, private void parseSub(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) { final XContentParser.Token token = parser.currentToken(); switch (token) { - case START_OBJECT: + case START_OBJECT -> { parseValue(parser, fieldParser, currentFieldName, value, context); /* * Well behaving parsers should consume the entire object but @@ -655,8 +642,8 @@ private void parseSub(XContentParser parser, FieldParser fieldParser, String cur if (parser.currentToken() != XContentParser.Token.END_OBJECT) { throwMustEndOn(currentFieldName, XContentParser.Token.END_OBJECT); } - break; - case START_ARRAY: + } + case START_ARRAY -> { parseArray(parser, fieldParser, currentFieldName, value, context); /* * Well behaving parsers should consume the entire array but @@ -669,17 +656,15 @@ private void parseSub(XContentParser parser, FieldParser fieldParser, String cur if (parser.currentToken() != XContentParser.Token.END_ARRAY) { throwMustEndOn(currentFieldName, XContentParser.Token.END_ARRAY); } - break; - case END_OBJECT: - case END_ARRAY: - case FIELD_NAME: - throw throwUnexpectedToken(parser, token); - case VALUE_STRING: - case VALUE_NUMBER: - case VALUE_BOOLEAN: - case VALUE_EMBEDDED_OBJECT: - case VALUE_NULL: - parseValue(parser, fieldParser, currentFieldName, value, context); + } + case END_OBJECT, END_ARRAY, FIELD_NAME -> throw throwUnexpectedToken(parser, token); + case VALUE_STRING, VALUE_NUMBER, VALUE_BOOLEAN, VALUE_EMBEDDED_OBJECT, VALUE_NULL -> parseValue( + parser, + fieldParser, + currentFieldName, + value, + context + ); } } diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentGenerator.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentGenerator.java index f4ecaebbb8a74..92c2b781287ce 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentGenerator.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentGenerator.java @@ -137,18 +137,10 @@ default void copyCurrentEvent(XContentParser parser) throws IOException { break; case VALUE_NUMBER: switch (parser.numberType()) { - case INT: - writeNumber(parser.intValue()); - break; - case LONG: - writeNumber(parser.longValue()); - break; - case FLOAT: - writeNumber(parser.floatValue()); - break; - case DOUBLE: - writeNumber(parser.doubleValue()); - break; + case INT -> writeNumber(parser.intValue()); + case LONG -> writeNumber(parser.longValue()); + case FLOAT -> writeNumber(parser.floatValue()); + case DOUBLE -> writeNumber(parser.doubleValue()); } break; case VALUE_BOOLEAN: diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentGenerator.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentGenerator.java index ca038f9466405..52f6029d03489 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentGenerator.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentGenerator.java @@ -413,21 +413,21 @@ private static void copyCurrentStructure(XContentGenerator destination, XContent } switch (token) { - case START_ARRAY: + case START_ARRAY -> { destination.writeStartArray(); while (parser.nextToken() != XContentParser.Token.END_ARRAY) { copyCurrentStructure(destination, parser); } destination.writeEndArray(); - break; - case START_OBJECT: + } + case START_OBJECT -> { destination.writeStartObject(); while (parser.nextToken() != XContentParser.Token.END_OBJECT) { copyCurrentStructure(destination, parser); } destination.writeEndObject(); - break; - default: // others are simple: + } + default -> // others are simple: destination.copyCurrentEvent(parser); } } diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentParser.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentParser.java index 13e2aeff45f7c..b42fcd642e3d2 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentParser.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/json/JsonXContentParser.java @@ -229,21 +229,14 @@ public void close() { } private NumberType convertNumberType(JsonParser.NumberType numberType) { - switch (numberType) { - case INT: - return NumberType.INT; - case BIG_INTEGER: - return NumberType.BIG_INTEGER; - case LONG: - return NumberType.LONG; - case FLOAT: - return NumberType.FLOAT; - case DOUBLE: - return NumberType.DOUBLE; - case BIG_DECIMAL: - return NumberType.BIG_DECIMAL; - } - throw new IllegalStateException("No matching token for number_type [" + numberType + "]"); + return switch (numberType) { + case INT -> NumberType.INT; + case BIG_INTEGER -> NumberType.BIG_INTEGER; + case LONG -> NumberType.LONG; + case FLOAT -> NumberType.FLOAT; + case DOUBLE -> NumberType.DOUBLE; + case BIG_DECIMAL -> NumberType.BIG_DECIMAL; + }; } private Token convertToken(JsonToken token) { diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/AbstractXContentParser.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/AbstractXContentParser.java index 27fc3d16ef788..d68790dd5f8fb 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/AbstractXContentParser.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/AbstractXContentParser.java @@ -81,14 +81,11 @@ void ensureNumberConversion(boolean coerce, long result, Class @Override public boolean isBooleanValue() throws IOException { - switch (currentToken()) { - case VALUE_BOOLEAN: - return true; - case VALUE_STRING: - return Booleans.isBoolean(textCharacters(), textOffset(), textLength()); - default: - return false; - } + return switch (currentToken()) { + case VALUE_BOOLEAN -> true; + case VALUE_STRING -> Booleans.isBoolean(textCharacters(), textOffset(), textLength()); + default -> false; + }; } @Override diff --git a/libs/x-content/src/test/java/org/elasticsearch/xcontent/MapXContentParserTests.java b/libs/x-content/src/test/java/org/elasticsearch/xcontent/MapXContentParserTests.java index 48d176dc9e955..4cac5c844d773 100644 --- a/libs/x-content/src/test/java/org/elasticsearch/xcontent/MapXContentParserTests.java +++ b/libs/x-content/src/test/java/org/elasticsearch/xcontent/MapXContentParserTests.java @@ -138,10 +138,8 @@ private void compareTokens(CheckedConsumer consume assertEquals(parser.textOrNull(), mapParser.textOrNull()); } switch (token) { - case VALUE_STRING: - assertEquals(parser.text(), mapParser.text()); - break; - case VALUE_NUMBER: + case VALUE_STRING -> assertEquals(parser.text(), mapParser.text()); + case VALUE_NUMBER -> { assertEquals(parser.numberType(), mapParser.numberType()); assertEquals(parser.numberValue(), mapParser.numberValue()); if (parser.numberType() == XContentParser.NumberType.LONG @@ -156,16 +154,10 @@ private void compareTokens(CheckedConsumer consume } else { assertEquals(parser.doubleValue(), mapParser.doubleValue(), 0.000001); } - break; - case VALUE_BOOLEAN: - assertEquals(parser.booleanValue(), mapParser.booleanValue()); - break; - case VALUE_EMBEDDED_OBJECT: - assertArrayEquals(parser.binaryValue(), mapParser.binaryValue()); - break; - case VALUE_NULL: - assertNull(mapParser.textOrNull()); - break; + } + case VALUE_BOOLEAN -> assertEquals(parser.booleanValue(), mapParser.booleanValue()); + case VALUE_EMBEDDED_OBJECT -> assertArrayEquals(parser.binaryValue(), mapParser.binaryValue()); + case VALUE_NULL -> assertNull(mapParser.textOrNull()); } assertEquals(parser.currentName(), mapParser.currentName()); assertEquals(parser.isClosed(), mapParser.isClosed()); diff --git a/libs/x-content/src/test/java/org/elasticsearch/xcontent/XContentParserTests.java b/libs/x-content/src/test/java/org/elasticsearch/xcontent/XContentParserTests.java index 7b063f404a068..1e815f93cc4a7 100644 --- a/libs/x-content/src/test/java/org/elasticsearch/xcontent/XContentParserTests.java +++ b/libs/x-content/src/test/java/org/elasticsearch/xcontent/XContentParserTests.java @@ -69,20 +69,9 @@ public void testFloat() throws IOException { assertEquals(value, number.floatValue(), 0.0f); switch (xContentType) { - case VND_CBOR: - case VND_SMILE: - case CBOR: - case SMILE: - assertThat(number, instanceOf(Float.class)); - break; - case VND_JSON: - case VND_YAML: - case JSON: - case YAML: - assertThat(number, instanceOf(Double.class)); - break; - default: - throw new AssertionError("unexpected x-content type [" + xContentType + "]"); + case VND_CBOR, VND_SMILE, CBOR, SMILE -> assertThat(number, instanceOf(Float.class)); + case VND_JSON, VND_YAML, JSON, YAML -> assertThat(number, instanceOf(Double.class)); + default -> throw new AssertionError("unexpected x-content type [" + xContentType + "]"); } } } diff --git a/libs/x-content/src/test/java/org/elasticsearch/xcontent/support/filtering/AbstractXContentFilteringTestCase.java b/libs/x-content/src/test/java/org/elasticsearch/xcontent/support/filtering/AbstractXContentFilteringTestCase.java index de64e7cc07cb9..c61b0794a8438 100644 --- a/libs/x-content/src/test/java/org/elasticsearch/xcontent/support/filtering/AbstractXContentFilteringTestCase.java +++ b/libs/x-content/src/test/java/org/elasticsearch/xcontent/support/filtering/AbstractXContentFilteringTestCase.java @@ -135,18 +135,12 @@ static void assertXContentBuilderAsBytes(final XContentBuilder expected, final X } assertThat(token1, equalTo(token2)); switch (token1) { - case FIELD_NAME: - assertThat(jsonParser.currentName(), equalTo(testParser.currentName())); - break; - case VALUE_STRING: - assertThat(jsonParser.text(), equalTo(testParser.text())); - break; - case VALUE_NUMBER: + case FIELD_NAME -> assertThat(jsonParser.currentName(), equalTo(testParser.currentName())); + case VALUE_STRING -> assertThat(jsonParser.text(), equalTo(testParser.text())); + case VALUE_NUMBER -> { assertThat(jsonParser.numberType(), equalTo(testParser.numberType())); assertThat(jsonParser.numberValue(), equalTo(testParser.numberValue())); - break; - default: - break; + } } } } catch (Exception e) { diff --git a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java index 78df56972c31d..123ebcf36a345 100644 --- a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java +++ b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java @@ -202,24 +202,16 @@ public Object getProperty(List path) { if (results == null) { return emptyMap(); } - switch (element) { - case "counts": - return results.getFieldCounts(); - case "means": - return results.getMeans(); - case "variances": - return results.getVariances(); - case "skewness": - return results.getSkewness(); - case "kurtosis": - return results.getKurtosis(); - case "covariance": - return results.getCovariances(); - case "correlation": - return results.getCorrelations(); - default: - throw new IllegalArgumentException("Found unknown path element [" + element + "] in [" + getName() + "]"); - } + return switch (element) { + case "counts" -> results.getFieldCounts(); + case "means" -> results.getMeans(); + case "variances" -> results.getVariances(); + case "skewness" -> results.getSkewness(); + case "kurtosis" -> results.getKurtosis(); + case "covariance" -> results.getCovariances(); + case "correlation" -> results.getCorrelations(); + default -> throw new IllegalArgumentException("Found unknown path element [" + element + "] in [" + getName() + "]"); + }; } else { throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path); } diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/CharGroupTokenizerFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/CharGroupTokenizerFactory.java index a079bcb8add54..a7e324f5bd54c 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/CharGroupTokenizerFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/CharGroupTokenizerFactory.java @@ -47,23 +47,12 @@ public CharGroupTokenizerFactory(IndexSettings indexSettings, Environment enviro tokenizeOnChars.add((int) parseEscapedChar(c)); } else { switch (c) { - case "letter": - tokenizeOnLetter = true; - break; - case "digit": - tokenizeOnDigit = true; - break; - case "whitespace": - tokenizeOnSpace = true; - break; - case "punctuation": - tokenizeOnPunctuation = true; - break; - case "symbol": - tokenizeOnSymbol = true; - break; - default: - throw new RuntimeException("Invalid escaped char in [" + c + "]"); + case "letter" -> tokenizeOnLetter = true; + case "digit" -> tokenizeOnDigit = true; + case "whitespace" -> tokenizeOnSpace = true; + case "punctuation" -> tokenizeOnPunctuation = true; + case "symbol" -> tokenizeOnSymbol = true; + default -> throw new RuntimeException("Invalid escaped char in [" + c + "]"); } } } diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/EdgeNGramTokenFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/EdgeNGramTokenFilterFactory.java index bbc2a3afcb589..56bd8c8e48631 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/EdgeNGramTokenFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/EdgeNGramTokenFilterFactory.java @@ -38,14 +38,11 @@ public class EdgeNGramTokenFilterFactory extends AbstractTokenFilterFactory { } static int parseSide(String side) { - switch (side) { - case "front": - return SIDE_FRONT; - case "back": - return SIDE_BACK; - default: - throw new IllegalArgumentException("invalid side: " + side); - } + return switch (side) { + case "front" -> SIDE_FRONT; + case "back" -> SIDE_BACK; + default -> throw new IllegalArgumentException("invalid side: " + side); + }; } @Override diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/MappingCharFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/MappingCharFilterFactory.java index 0142aa1be90c0..b32206831990c 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/MappingCharFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/MappingCharFilterFactory.java @@ -75,29 +75,17 @@ private String parseString(String s) { if (readPos >= len) throw new RuntimeException("Invalid escaped char in [" + s + "]"); c = s.charAt(readPos++); switch (c) { - case '\\': - c = '\\'; - break; - case 'n': - c = '\n'; - break; - case 't': - c = '\t'; - break; - case 'r': - c = '\r'; - break; - case 'b': - c = '\b'; - break; - case 'f': - c = '\f'; - break; - case 'u': + case '\\' -> c = '\\'; + case 'n' -> c = '\n'; + case 't' -> c = '\t'; + case 'r' -> c = '\r'; + case 'b' -> c = '\b'; + case 'f' -> c = '\f'; + case 'u' -> { if (readPos + 3 >= len) throw new RuntimeException("Invalid escaped char in [" + s + "]"); c = (char) Integer.parseInt(s.substring(readPos, readPos + 4), 16); readPos += 4; - break; + } } } out[writePos++] = c; diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java index f4d1ed1e2ea8f..98d24b2507c01 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java @@ -151,29 +151,17 @@ private static String parseString(String s) { if (readPos >= len) throw new RuntimeException("Invalid escaped char in [" + s + "]"); c = s.charAt(readPos++); switch (c) { - case '\\': - c = '\\'; - break; - case 'n': - c = '\n'; - break; - case 't': - c = '\t'; - break; - case 'r': - c = '\r'; - break; - case 'b': - c = '\b'; - break; - case 'f': - c = '\f'; - break; - case 'u': + case '\\' -> c = '\\'; + case 'n' -> c = '\n'; + case 't' -> c = '\t'; + case 'r' -> c = '\r'; + case 'b' -> c = '\b'; + case 'f' -> c = '\f'; + case 'u' -> { if (readPos + 3 >= len) throw new RuntimeException("Invalid escaped char in [" + s + "]"); c = (char) Integer.parseInt(s.substring(readPos, readPos + 4), 16); readPos += 4; - break; + } } } out[writePos++] = c; diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CommunityIdProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CommunityIdProcessor.java index 848656d3caa2a..27ef5a10dd5c2 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CommunityIdProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CommunityIdProcessor.java @@ -226,25 +226,21 @@ private static Flow buildFlow( flow.protocol = Transport.fromObject(protocol); switch (flow.protocol) { - case Tcp: - case Udp: - case Sctp: + case Tcp, Udp, Sctp -> { flow.sourcePort = parseIntFromObjectOrString(sourcePort.get(), "source port"); if (flow.sourcePort < 1 || flow.sourcePort > 65535) { throw new IllegalArgumentException("invalid source port [" + sourcePort.get() + "]"); } - flow.destinationPort = parseIntFromObjectOrString(destinationPort.get(), "destination port"); if (flow.destinationPort < 1 || flow.destinationPort > 65535) { throw new IllegalArgumentException("invalid destination port [" + destinationPort.get() + "]"); } - break; - case Icmp: - case IcmpIpV6: + } + case Icmp, IcmpIpV6 -> { // tolerate missing or invalid ICMP types and codes flow.icmpType = parseIntFromObjectOrString(icmpType, "icmp type"); flow.icmpCode = parseIntFromObjectOrString(icmpCode, "icmp code"); - break; + } } return flow; @@ -441,30 +437,19 @@ public int getTransportNumber() { } public static Transport fromNumber(int transportNumber) { - switch (transportNumber) { - case 1: - return Icmp; - case 2: - return Igmp; - case 6: - return Tcp; - case 17: - return Udp; - case 47: - return Gre; - case 58: - return IcmpIpV6; - case 88: - return Eigrp; - case 89: - return Ospf; - case 103: - return Pim; - case 132: - return Sctp; - default: - throw new IllegalArgumentException("unknown transport protocol number [" + transportNumber + "]"); - } + return switch (transportNumber) { + case 1 -> Icmp; + case 2 -> Igmp; + case 6 -> Tcp; + case 17 -> Udp; + case 47 -> Gre; + case 58 -> IcmpIpV6; + case 88 -> Eigrp; + case 89 -> Ospf; + case 103 -> Pim; + case 132 -> Sctp; + default -> throw new IllegalArgumentException("unknown transport protocol number [" + transportNumber + "]"); + }; } public static Transport fromObject(Object o) { @@ -557,55 +542,33 @@ public int getType() { } public static IcmpType fromNumber(int type) { - switch (type) { - case 0: - return EchoReply; - case 8: - return EchoRequest; - case 9: - return RouterAdvertisement; - case 10: - return RouterSolicitation; - case 13: - return TimestampRequest; - case 14: - return TimestampReply; - case 15: - return InfoRequest; - case 16: - return InfoReply; - case 17: - return AddressMaskRequest; - case 18: - return AddressMaskReply; - case 128: - return V6EchoRequest; - case 129: - return V6EchoReply; - case 133: - return V6RouterSolicitation; - case 134: - return V6RouterAdvertisement; - case 135: - return V6NeighborSolicitation; - case 136: - return V6NeighborAdvertisement; - case 130: - return V6MLDv1MulticastListenerQueryMessage; - case 131: - return V6MLDv1MulticastListenerReportMessage; - case 139: - return V6WhoAreYouRequest; - case 140: - return V6WhoAreYouReply; - case 144: - return V6HomeAddressDiscoveryRequest; - case 145: - return V6HomeAddressDiscoveryResponse; - default: + return switch (type) { + case 0 -> EchoReply; + case 8 -> EchoRequest; + case 9 -> RouterAdvertisement; + case 10 -> RouterSolicitation; + case 13 -> TimestampRequest; + case 14 -> TimestampReply; + case 15 -> InfoRequest; + case 16 -> InfoReply; + case 17 -> AddressMaskRequest; + case 18 -> AddressMaskReply; + case 128 -> V6EchoRequest; + case 129 -> V6EchoReply; + case 133 -> V6RouterSolicitation; + case 134 -> V6RouterAdvertisement; + case 135 -> V6NeighborSolicitation; + case 136 -> V6NeighborAdvertisement; + case 130 -> V6MLDv1MulticastListenerQueryMessage; + case 131 -> V6MLDv1MulticastListenerReportMessage; + case 139 -> V6WhoAreYouRequest; + case 140 -> V6WhoAreYouReply; + case 144 -> V6HomeAddressDiscoveryRequest; + case 145 -> V6HomeAddressDiscoveryResponse; + default -> // don't fail if the type is unknown - return EchoReply; - } + EchoReply; + }; } public static Integer codeEquivalent(int icmpType, boolean isIpV6) { diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CsvParser.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CsvParser.java index 6739ce5a41b4e..69ee801b58d83 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CsvParser.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CsvParser.java @@ -75,14 +75,9 @@ void process(String line) { // we've reached end of string, we need to handle last field switch (state) { - case UNQUOTED: - setField(length); - break; - case QUOTED_END: - setField(length - 1); - break; - case QUOTED: - throw new IllegalArgumentException("Unmatched quote"); + case UNQUOTED -> setField(length); + case QUOTED_END -> setField(length - 1); + case QUOTED -> throw new IllegalArgumentException("Unmatched quote"); } } diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DateFormat.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DateFormat.java index a9bc6c2e88c3d..8ee203f935901 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DateFormat.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DateFormat.java @@ -118,17 +118,12 @@ Function getFunction(String format, ZoneId zoneId, Locale abstract Function getFunction(String format, ZoneId timezone, Locale locale); static DateFormat fromString(String format) { - switch (format) { - case "ISO8601": - return Iso8601; - case "UNIX": - return Unix; - case "UNIX_MS": - return UnixMs; - case "TAI64N": - return Tai64n; - default: - return Java; - } + return switch (format) { + case "ISO8601" -> Iso8601; + case "UNIX" -> Unix; + case "UNIX_MS" -> UnixMs; + case "TAI64N" -> Tai64n; + default -> Java; + }; } } diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/NetworkDirectionProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/NetworkDirectionProcessor.java index 8b40bfee544b7..954d57a8a2a01 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/NetworkDirectionProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/NetworkDirectionProcessor.java @@ -165,29 +165,18 @@ private boolean isInternal(List networks, String ip) { private boolean inNetwork(String ip, String network) { InetAddress address = InetAddresses.forString(ip); - switch (network) { - case LOOPBACK_NAMED_NETWORK: - return isLoopback(address); - case GLOBAL_UNICAST_NAMED_NETWORK: - case UNICAST_NAMED_NETWORK: - return isUnicast(address); - case LINK_LOCAL_UNICAST_NAMED_NETWORK: - return isLinkLocalUnicast(address); - case INTERFACE_LOCAL_NAMED_NETWORK: - return isInterfaceLocalMulticast(address); - case LINK_LOCAL_MULTICAST_NAMED_NETWORK: - return isLinkLocalMulticast(address); - case MULTICAST_NAMED_NETWORK: - return isMulticast(address); - case UNSPECIFIED_NAMED_NETWORK: - return isUnspecified(address); - case PRIVATE_NAMED_NETWORK: - return isPrivate(ip); - case PUBLIC_NAMED_NETWORK: - return isPublic(ip); - default: - return CIDRUtils.isInRange(ip, network); - } + return switch (network) { + case LOOPBACK_NAMED_NETWORK -> isLoopback(address); + case GLOBAL_UNICAST_NAMED_NETWORK, UNICAST_NAMED_NETWORK -> isUnicast(address); + case LINK_LOCAL_UNICAST_NAMED_NETWORK -> isLinkLocalUnicast(address); + case INTERFACE_LOCAL_NAMED_NETWORK -> isInterfaceLocalMulticast(address); + case LINK_LOCAL_MULTICAST_NAMED_NETWORK -> isLinkLocalMulticast(address); + case MULTICAST_NAMED_NETWORK -> isMulticast(address); + case UNSPECIFIED_NAMED_NETWORK -> isUnspecified(address); + case PRIVATE_NAMED_NETWORK -> isPrivate(ip); + case PUBLIC_NAMED_NETWORK -> isPublic(ip); + default -> CIDRUtils.isInRange(ip, network); + }; } private boolean isLoopback(InetAddress ip) { diff --git a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ConvertProcessorTests.java b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ConvertProcessorTests.java index 3771718947a5f..dbe8e6a87ca18 100644 --- a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ConvertProcessorTests.java +++ b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ConvertProcessorTests.java @@ -383,23 +383,22 @@ public void testConvertString() throws Exception { Object fieldValue; String expectedFieldValue; switch (randomIntBetween(0, 2)) { - case 0: + case 0 -> { float randomFloat = randomFloat(); fieldValue = randomFloat; expectedFieldValue = Float.toString(randomFloat); - break; - case 1: + } + case 1 -> { int randomInt = randomInt(); fieldValue = randomInt; expectedFieldValue = Integer.toString(randomInt); - break; - case 2: + } + case 2 -> { boolean randomBoolean = randomBoolean(); fieldValue = randomBoolean; expectedFieldValue = Boolean.toString(randomBoolean); - break; - default: - throw new UnsupportedOperationException(); + } + default -> throw new UnsupportedOperationException(); } String fieldName = RandomDocumentPicks.addRandomField(random(), ingestDocument, fieldValue); @@ -417,33 +416,32 @@ public void testConvertStringList() throws Exception { Object randomValue; String randomValueString; switch (randomIntBetween(0, 2)) { - case 0: + case 0 -> { float randomFloat = randomFloat(); randomValue = randomFloat; randomValueString = Float.toString(randomFloat); - break; - case 1: + } + case 1 -> { int randomInt = randomInt(); randomValue = randomInt; randomValueString = Integer.toString(randomInt); - break; - case 2: + } + case 2 -> { boolean randomBoolean = randomBoolean(); randomValue = randomBoolean; randomValueString = Boolean.toString(randomBoolean); - break; - case 3: + } + case 3 -> { long randomLong = randomLong(); randomValue = randomLong; randomValueString = Long.toString(randomLong); - break; - case 4: + } + case 4 -> { double randomDouble = randomDouble(); randomValue = randomDouble; randomValueString = Double.toString(randomDouble); - break; - default: - throw new UnsupportedOperationException(); + } + default -> throw new UnsupportedOperationException(); } fieldValue.add(randomValue); expectedList.add(randomValueString); @@ -501,20 +499,19 @@ public void testConvertNullFieldWithIgnoreMissing() throws Exception { public void testAutoConvertNotString() throws Exception { Object randomValue; switch (randomIntBetween(0, 2)) { - case 0: + case 0 -> { float randomFloat = randomFloat(); randomValue = randomFloat; - break; - case 1: + } + case 1 -> { int randomInt = randomInt(); randomValue = randomInt; - break; - case 2: + } + case 2 -> { boolean randomBoolean = randomBoolean(); randomValue = randomBoolean; - break; - default: - throw new UnsupportedOperationException(); + } + default -> throw new UnsupportedOperationException(); } IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), Collections.singletonMap("field", randomValue)); Processor processor = new ConvertProcessor(randomAlphaOfLength(10), null, "field", "field", Type.AUTO, false); diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java index 1cd41c60fb7a3..0328dabf46a99 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java @@ -224,28 +224,26 @@ private Map retrieveCityGeoData(DatabaseReaderLazyLoader lazyLoa Map geoData = new HashMap<>(); for (Property property : this.properties) { switch (property) { - case IP: - geoData.put("ip", NetworkAddress.format(ipAddress)); - break; - case COUNTRY_ISO_CODE: + case IP -> geoData.put("ip", NetworkAddress.format(ipAddress)); + case COUNTRY_ISO_CODE -> { String countryIsoCode = country.getIsoCode(); if (countryIsoCode != null) { geoData.put("country_iso_code", countryIsoCode); } - break; - case COUNTRY_NAME: + } + case COUNTRY_NAME -> { String countryName = country.getName(); if (countryName != null) { geoData.put("country_name", countryName); } - break; - case CONTINENT_NAME: + } + case CONTINENT_NAME -> { String continentName = continent.getName(); if (continentName != null) { geoData.put("continent_name", continentName); } - break; - case REGION_ISO_CODE: + } + case REGION_ISO_CODE -> { // ISO 3166-2 code for country subdivisions. // See iso.org/iso-3166-country-codes.html String countryIso = country.getIsoCode(); @@ -254,26 +252,26 @@ private Map retrieveCityGeoData(DatabaseReaderLazyLoader lazyLoa String regionIsoCode = countryIso + "-" + subdivisionIso; geoData.put("region_iso_code", regionIsoCode); } - break; - case REGION_NAME: + } + case REGION_NAME -> { String subdivisionName = subdivision.getName(); if (subdivisionName != null) { geoData.put("region_name", subdivisionName); } - break; - case CITY_NAME: + } + case CITY_NAME -> { String cityName = city.getName(); if (cityName != null) { geoData.put("city_name", cityName); } - break; - case TIMEZONE: + } + case TIMEZONE -> { String locationTimeZone = location.getTimeZone(); if (locationTimeZone != null) { geoData.put("timezone", locationTimeZone); } - break; - case LOCATION: + } + case LOCATION -> { Double latitude = location.getLatitude(); Double longitude = location.getLongitude(); if (latitude != null && longitude != null) { @@ -282,7 +280,7 @@ private Map retrieveCityGeoData(DatabaseReaderLazyLoader lazyLoa locationObject.put("lon", longitude); geoData.put("location", locationObject); } - break; + } } } return geoData; @@ -299,27 +297,25 @@ private Map retrieveCountryGeoData(DatabaseReaderLazyLoader lazy Map geoData = new HashMap<>(); for (Property property : this.properties) { switch (property) { - case IP: - geoData.put("ip", NetworkAddress.format(ipAddress)); - break; - case COUNTRY_ISO_CODE: + case IP -> geoData.put("ip", NetworkAddress.format(ipAddress)); + case COUNTRY_ISO_CODE -> { String countryIsoCode = country.getIsoCode(); if (countryIsoCode != null) { geoData.put("country_iso_code", countryIsoCode); } - break; - case COUNTRY_NAME: + } + case COUNTRY_NAME -> { String countryName = country.getName(); if (countryName != null) { geoData.put("country_name", countryName); } - break; - case CONTINENT_NAME: + } + case CONTINENT_NAME -> { String continentName = continent.getName(); if (continentName != null) { geoData.put("continent_name", continentName); } - break; + } } } return geoData; diff --git a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateField.java b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateField.java index 0bb94a26d5531..de29788850899 100644 --- a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateField.java +++ b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateField.java @@ -45,52 +45,36 @@ private DateField() {} static final String GET_SECONDS_METHOD = "getSeconds"; static DoubleValuesSource getVariable(IndexFieldData fieldData, String fieldName, String variable) { - switch (variable) { - case VALUE_VARIABLE: - return new FieldDataValueSource(fieldData, MultiValueMode.MIN); - case EMPTY_VARIABLE: - return new EmptyMemberValueSource(fieldData); - case LENGTH_VARIABLE: - return new CountMethodValueSource(fieldData); - default: - throw new IllegalArgumentException("Member variable [" + variable + "] does not exist for date field [" + fieldName + "]."); - } + return switch (variable) { + case VALUE_VARIABLE -> new FieldDataValueSource(fieldData, MultiValueMode.MIN); + case EMPTY_VARIABLE -> new EmptyMemberValueSource(fieldData); + case LENGTH_VARIABLE -> new CountMethodValueSource(fieldData); + default -> throw new IllegalArgumentException( + "Member variable [" + variable + "] does not exist for date field [" + fieldName + "]." + ); + }; } static DoubleValuesSource getMethod(IndexFieldData fieldData, String fieldName, String method) { - switch (method) { - case GETVALUE_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MIN); - case ISEMPTY_METHOD: - return new EmptyMemberValueSource(fieldData); - case SIZE_METHOD: - return new CountMethodValueSource(fieldData); - case MINIMUM_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MIN); - case MAXIMUM_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MAX); - case AVERAGE_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.AVG); - case MEDIAN_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MEDIAN); - case SUM_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.SUM); - case COUNT_METHOD: - return new CountMethodValueSource(fieldData); - case GET_YEAR_METHOD: - return new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.YEAR); - case GET_MONTH_METHOD: - return new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.MONTH); - case GET_DAY_OF_MONTH_METHOD: - return new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.DAY_OF_MONTH); - case GET_HOUR_OF_DAY_METHOD: - return new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.HOUR_OF_DAY); - case GET_MINUTES_METHOD: - return new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.MINUTE); - case GET_SECONDS_METHOD: - return new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.SECOND); - default: - throw new IllegalArgumentException("Member method [" + method + "] does not exist for date field [" + fieldName + "]."); - } + return switch (method) { + case GETVALUE_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MIN); + case ISEMPTY_METHOD -> new EmptyMemberValueSource(fieldData); + case SIZE_METHOD -> new CountMethodValueSource(fieldData); + case MINIMUM_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MIN); + case MAXIMUM_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MAX); + case AVERAGE_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.AVG); + case MEDIAN_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MEDIAN); + case SUM_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.SUM); + case COUNT_METHOD -> new CountMethodValueSource(fieldData); + case GET_YEAR_METHOD -> new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.YEAR); + case GET_MONTH_METHOD -> new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.MONTH); + case GET_DAY_OF_MONTH_METHOD -> new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.DAY_OF_MONTH); + case GET_HOUR_OF_DAY_METHOD -> new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.HOUR_OF_DAY); + case GET_MINUTES_METHOD -> new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.MINUTE); + case GET_SECONDS_METHOD -> new DateMethodValueSource(fieldData, MultiValueMode.MIN, method, Calendar.SECOND); + default -> throw new IllegalArgumentException( + "Member method [" + method + "] does not exist for date field [" + fieldName + "]." + ); + }; } } diff --git a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateObject.java b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateObject.java index 3a8864fa3a9dc..48fbdc1094dbd 100644 --- a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateObject.java +++ b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/DateObject.java @@ -64,112 +64,154 @@ private DateObject() {} static final String GETYEAR_OF_ERA_METHOD = "getYearOfEra"; static DoubleValuesSource getVariable(IndexFieldData fieldData, String fieldName, String variable) { - switch (variable) { - case CENTURY_OF_ERA_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.YEAR_OF_ERA) / 100); - case DAY_OF_MONTH_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getDayOfMonth); - case DAY_OF_WEEK_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.getDayOfWeek().getValue()); - case DAY_OF_YEAR_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getDayOfYear); - case ERA_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.ERA)); - case HOUR_OF_DAY_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getHour); - case MILLIS_OF_DAY_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.MILLI_OF_DAY)); - case MILLIS_OF_SECOND_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.MILLI_OF_SECOND)); - case MINUTE_OF_DAY_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.MINUTE_OF_DAY)); - case MINUTE_OF_HOUR_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getMinute); - case MONTH_OF_YEAR_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getMonthValue); - case SECOND_OF_DAY_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.SECOND_OF_DAY)); - case SECOND_OF_MINUTE_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getSecond); - case WEEK_OF_WEEK_YEAR_VARIABLE: - return new DateObjectValueSource( - fieldData, - MultiValueMode.MIN, - variable, - zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekOfWeekBasedYear()) - ); - case WEEK_YEAR_VARIABLE: - return new DateObjectValueSource( - fieldData, - MultiValueMode.MIN, - variable, - zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekBasedYear()) - ); - case YEAR_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getYear); - case YEAR_OF_CENTURY_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.YEAR_OF_ERA) % 100); - case YEAR_OF_ERA_VARIABLE: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.YEAR_OF_ERA)); - default: - throw new IllegalArgumentException( - "Member variable [" + variable + "] does not exist for date object on field [" + fieldName + "]." - ); - } + return switch (variable) { + case CENTURY_OF_ERA_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.YEAR_OF_ERA) / 100 + ); + case DAY_OF_MONTH_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getDayOfMonth); + case DAY_OF_WEEK_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.getDayOfWeek().getValue() + ); + case DAY_OF_YEAR_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getDayOfYear); + case ERA_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, zdt -> zdt.get(ChronoField.ERA)); + case HOUR_OF_DAY_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getHour); + case MILLIS_OF_DAY_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.MILLI_OF_DAY) + ); + case MILLIS_OF_SECOND_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.MILLI_OF_SECOND) + ); + case MINUTE_OF_DAY_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.MINUTE_OF_DAY) + ); + case MINUTE_OF_HOUR_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getMinute); + case MONTH_OF_YEAR_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getMonthValue); + case SECOND_OF_DAY_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.SECOND_OF_DAY) + ); + case SECOND_OF_MINUTE_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getSecond); + case WEEK_OF_WEEK_YEAR_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekOfWeekBasedYear()) + ); + case WEEK_YEAR_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekBasedYear()) + ); + case YEAR_VARIABLE -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, variable, ZonedDateTime::getYear); + case YEAR_OF_CENTURY_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.YEAR_OF_ERA) % 100 + ); + case YEAR_OF_ERA_VARIABLE -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + variable, + zdt -> zdt.get(ChronoField.YEAR_OF_ERA) + ); + default -> throw new IllegalArgumentException( + "Member variable [" + variable + "] does not exist for date object on field [" + fieldName + "]." + ); + }; } static DoubleValuesSource getMethod(IndexFieldData fieldData, String fieldName, String method) { - switch (method) { - case GETCENTURY_OF_ERA_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.YEAR_OF_ERA) / 100); - case GETDAY_OF_MONTH_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getDayOfMonth); - case GETDAY_OF_WEEK_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.getDayOfWeek().getValue()); - case GETDAY_OF_YEAR_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getDayOfYear); - case GETERA_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.ERA)); - case GETHOUR_OF_DAY_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getHour); - case GETMILLIS_OF_DAY_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.MILLI_OF_DAY)); - case GETMILLIS_OF_SECOND_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.MILLI_OF_SECOND)); - case GETMINUTE_OF_DAY_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.MINUTE_OF_DAY)); - case GETMINUTE_OF_HOUR_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getMinute); - case GETMONTH_OF_YEAR_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getMonthValue); - case GETSECOND_OF_DAY_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.SECOND_OF_DAY)); - case GETSECOND_OF_MINUTE_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getSecond); - case GETWEEK_OF_WEEK_YEAR_METHOD: - return new DateObjectValueSource( - fieldData, - MultiValueMode.MIN, - method, - zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekOfWeekBasedYear()) - ); - case GETWEEK_YEAR_METHOD: - return new DateObjectValueSource( - fieldData, - MultiValueMode.MIN, - method, - zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekBasedYear()) - ); - case GETYEAR_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getYear); - case GETYEAR_OF_CENTURY_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.YEAR_OF_ERA) % 100); - case GETYEAR_OF_ERA_METHOD: - return new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.YEAR_OF_ERA)); - default: - throw new IllegalArgumentException( - "Member method [" + method + "] does not exist for date object on field [" + fieldName + "]." - ); - } + return switch (method) { + case GETCENTURY_OF_ERA_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.YEAR_OF_ERA) / 100 + ); + case GETDAY_OF_MONTH_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getDayOfMonth); + case GETDAY_OF_WEEK_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.getDayOfWeek().getValue() + ); + case GETDAY_OF_YEAR_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getDayOfYear); + case GETERA_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, zdt -> zdt.get(ChronoField.ERA)); + case GETHOUR_OF_DAY_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getHour); + case GETMILLIS_OF_DAY_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.MILLI_OF_DAY) + ); + case GETMILLIS_OF_SECOND_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.MILLI_OF_SECOND) + ); + case GETMINUTE_OF_DAY_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.MINUTE_OF_DAY) + ); + case GETMINUTE_OF_HOUR_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getMinute); + case GETMONTH_OF_YEAR_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getMonthValue); + case GETSECOND_OF_DAY_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.SECOND_OF_DAY) + ); + case GETSECOND_OF_MINUTE_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getSecond); + case GETWEEK_OF_WEEK_YEAR_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekOfWeekBasedYear()) + ); + case GETWEEK_YEAR_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(DateFormatters.WEEK_FIELDS_ROOT.weekBasedYear()) + ); + case GETYEAR_METHOD -> new DateObjectValueSource(fieldData, MultiValueMode.MIN, method, ZonedDateTime::getYear); + case GETYEAR_OF_CENTURY_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.YEAR_OF_ERA) % 100 + ); + case GETYEAR_OF_ERA_METHOD -> new DateObjectValueSource( + fieldData, + MultiValueMode.MIN, + method, + zdt -> zdt.get(ChronoField.YEAR_OF_ERA) + ); + default -> throw new IllegalArgumentException( + "Member method [" + method + "] does not exist for date object on field [" + fieldName + "]." + ); + }; } } diff --git a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/GeoField.java b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/GeoField.java index a107d1386d4a7..63ea46238e679 100644 --- a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/GeoField.java +++ b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/GeoField.java @@ -29,28 +29,24 @@ private GeoField() {} static final String GETLON_METHOD = "getLon"; static DoubleValuesSource getVariable(IndexFieldData fieldData, String fieldName, String variable) { - switch (variable) { - case EMPTY_VARIABLE: - return new GeoEmptyValueSource(fieldData); - case LAT_VARIABLE: - return new GeoLatitudeValueSource(fieldData); - case LON_VARIABLE: - return new GeoLongitudeValueSource(fieldData); - default: - throw new IllegalArgumentException("Member variable [" + variable + "] does not exist for geo field [" + fieldName + "]."); - } + return switch (variable) { + case EMPTY_VARIABLE -> new GeoEmptyValueSource(fieldData); + case LAT_VARIABLE -> new GeoLatitudeValueSource(fieldData); + case LON_VARIABLE -> new GeoLongitudeValueSource(fieldData); + default -> throw new IllegalArgumentException( + "Member variable [" + variable + "] does not exist for geo field [" + fieldName + "]." + ); + }; } static DoubleValuesSource getMethod(IndexFieldData fieldData, String fieldName, String method) { - switch (method) { - case ISEMPTY_METHOD: - return new GeoEmptyValueSource(fieldData); - case GETLAT_METHOD: - return new GeoLatitudeValueSource(fieldData); - case GETLON_METHOD: - return new GeoLongitudeValueSource(fieldData); - default: - throw new IllegalArgumentException("Member method [" + method + "] does not exist for geo field [" + fieldName + "]."); - } + return switch (method) { + case ISEMPTY_METHOD -> new GeoEmptyValueSource(fieldData); + case GETLAT_METHOD -> new GeoLatitudeValueSource(fieldData); + case GETLON_METHOD -> new GeoLongitudeValueSource(fieldData); + default -> throw new IllegalArgumentException( + "Member method [" + method + "] does not exist for geo field [" + fieldName + "]." + ); + }; } } diff --git a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/NumericField.java b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/NumericField.java index 563ca0080b8c6..387b6fd7d939d 100644 --- a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/NumericField.java +++ b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/NumericField.java @@ -36,42 +36,30 @@ private NumericField() {} static final String COUNT_METHOD = "count"; static DoubleValuesSource getVariable(IndexFieldData fieldData, String fieldName, String variable) { - switch (variable) { - case VALUE_VARIABLE: - return new FieldDataValueSource(fieldData, MultiValueMode.MIN); - case EMPTY_VARIABLE: - return new EmptyMemberValueSource(fieldData); - case LENGTH_VARIABLE: - return new CountMethodValueSource(fieldData); - default: - throw new IllegalArgumentException( - "Member variable [" + variable + "] does not exist for " + "numeric field [" + fieldName + "]." - ); - } + return switch (variable) { + case VALUE_VARIABLE -> new FieldDataValueSource(fieldData, MultiValueMode.MIN); + case EMPTY_VARIABLE -> new EmptyMemberValueSource(fieldData); + case LENGTH_VARIABLE -> new CountMethodValueSource(fieldData); + default -> throw new IllegalArgumentException( + "Member variable [" + variable + "] does not exist for " + "numeric field [" + fieldName + "]." + ); + }; } static DoubleValuesSource getMethod(IndexFieldData fieldData, String fieldName, String method) { - switch (method) { - case GETVALUE_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MIN); - case ISEMPTY_METHOD: - return new EmptyMemberValueSource(fieldData); - case SIZE_METHOD: - return new CountMethodValueSource(fieldData); - case MINIMUM_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MIN); - case MAXIMUM_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MAX); - case AVERAGE_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.AVG); - case MEDIAN_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.MEDIAN); - case SUM_METHOD: - return new FieldDataValueSource(fieldData, MultiValueMode.SUM); - case COUNT_METHOD: - return new CountMethodValueSource(fieldData); - default: - throw new IllegalArgumentException("Member method [" + method + "] does not exist for numeric field [" + fieldName + "]."); - } + return switch (method) { + case GETVALUE_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MIN); + case ISEMPTY_METHOD -> new EmptyMemberValueSource(fieldData); + case SIZE_METHOD -> new CountMethodValueSource(fieldData); + case MINIMUM_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MIN); + case MAXIMUM_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MAX); + case AVERAGE_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.AVG); + case MEDIAN_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.MEDIAN); + case SUM_METHOD -> new FieldDataValueSource(fieldData, MultiValueMode.SUM); + case COUNT_METHOD -> new CountMethodValueSource(fieldData); + default -> throw new IllegalArgumentException( + "Member method [" + method + "] does not exist for numeric field [" + fieldName + "]." + ); + }; } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/DefBootstrap.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/DefBootstrap.java index 1aea004e92cf5..6d86bf431ab7c 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/DefBootstrap.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/DefBootstrap.java @@ -156,34 +156,34 @@ static boolean checkClass(Class clazz, Object receiver) { * Does a slow lookup against the whitelist. */ private MethodHandle lookup(int flavorValue, String nameValue, Class receiver) throws Throwable { - switch (flavorValue) { - case METHOD_CALL: - return Def.lookupMethod(painlessLookup, functions, constants, methodHandlesLookup, type(), receiver, nameValue, args); - case LOAD: - return Def.lookupGetter(painlessLookup, receiver, nameValue); - case STORE: - return Def.lookupSetter(painlessLookup, receiver, nameValue); - case ARRAY_LOAD: - return Def.lookupArrayLoad(receiver); - case ARRAY_STORE: - return Def.lookupArrayStore(receiver); - case ITERATOR: - return Def.lookupIterator(receiver); - case REFERENCE: - return Def.lookupReference( - painlessLookup, - functions, - constants, - methodHandlesLookup, - (String) args[0], - receiver, - nameValue - ); - case INDEX_NORMALIZE: - return Def.lookupIndexNormalize(receiver); - default: - throw new AssertionError(); - } + return switch (flavorValue) { + case METHOD_CALL -> Def.lookupMethod( + painlessLookup, + functions, + constants, + methodHandlesLookup, + type(), + receiver, + nameValue, + args + ); + case LOAD -> Def.lookupGetter(painlessLookup, receiver, nameValue); + case STORE -> Def.lookupSetter(painlessLookup, receiver, nameValue); + case ARRAY_LOAD -> Def.lookupArrayLoad(receiver); + case ARRAY_STORE -> Def.lookupArrayStore(receiver); + case ITERATOR -> Def.lookupIterator(receiver); + case REFERENCE -> Def.lookupReference( + painlessLookup, + functions, + constants, + methodHandlesLookup, + (String) args[0], + receiver, + nameValue + ); + case INDEX_NORMALIZE -> Def.lookupIndexNormalize(receiver); + default -> throw new AssertionError(); + }; } /** @@ -493,7 +493,7 @@ public static CallSite bootstrap( // validate arguments switch (flavor) { // "function-call" like things get a polymorphic cache - case METHOD_CALL: + case METHOD_CALL -> { if (args.length == 0) { throw new BootstrapMethodError("Invalid number of parameters for method call"); } @@ -509,17 +509,14 @@ public static CallSite bootstrap( throw new BootstrapMethodError("Illegal number of parameters: expected " + numLambdas + " references"); } return new PIC(painlessLookup, functions, constants, methodHandlesLookup, name, type, initialDepth, flavor, args); - case LOAD: - case STORE: - case ARRAY_LOAD: - case ARRAY_STORE: - case ITERATOR: - case INDEX_NORMALIZE: + } + case LOAD, STORE, ARRAY_LOAD, ARRAY_STORE, ITERATOR, INDEX_NORMALIZE -> { if (args.length > 0) { throw new BootstrapMethodError("Illegal static bootstrap parameters for flavor: " + flavor); } return new PIC(painlessLookup, functions, constants, methodHandlesLookup, name, type, initialDepth, flavor, args); - case REFERENCE: + } + case REFERENCE -> { if (args.length != 1) { throw new BootstrapMethodError("Invalid number of parameters for reference call"); } @@ -527,11 +524,10 @@ public static CallSite bootstrap( throw new BootstrapMethodError("Illegal parameter for reference call: " + args[0]); } return new PIC(painlessLookup, functions, constants, methodHandlesLookup, name, type, initialDepth, flavor, args); + } // operators get monomorphic cache, with a generic impl for a fallback - case UNARY_OPERATOR: - case SHIFT_OPERATOR: - case BINARY_OPERATOR: + case UNARY_OPERATOR, SHIFT_OPERATOR, BINARY_OPERATOR -> { if (args.length != 1) { throw new BootstrapMethodError("Invalid number of parameters for operator call"); } @@ -548,8 +544,8 @@ public static CallSite bootstrap( throw new BootstrapMethodError("This parameter is only supported for BINARY/SHIFT_OPERATORs"); } return new MIC(name, type, initialDepth, flavor, flags); - default: - throw new BootstrapMethodError("Illegal static bootstrap parameter for flavor: " + flavor); + } + default -> throw new BootstrapMethodError("Illegal static bootstrap parameter for flavor: " + flavor); } } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java index 93e9ce5415561..58d9444a3e94d 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java @@ -331,16 +331,10 @@ public void writeDynamicBinaryInstruction( Type methodType = Type.getMethodType(getType(returnType), getType(lhs), getType(rhs)); switch (operation) { - case MUL: - invokeDefCall("mul", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case DIV: - invokeDefCall("div", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case REM: - invokeDefCall("rem", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case ADD: + case MUL -> invokeDefCall("mul", methodType, DefBootstrap.BINARY_OPERATOR, flags); + case DIV -> invokeDefCall("div", methodType, DefBootstrap.BINARY_OPERATOR, flags); + case REM -> invokeDefCall("rem", methodType, DefBootstrap.BINARY_OPERATOR, flags); + case ADD -> { // if either side is primitive, then the + operator should always throw NPE on null, // so we don't need a special NPE guard. // otherwise, we need to allow nulls for possible string concatenation. @@ -349,30 +343,15 @@ public void writeDynamicBinaryInstruction( flags |= DefBootstrap.OPERATOR_ALLOWS_NULL; } invokeDefCall("add", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case SUB: - invokeDefCall("sub", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case LSH: - invokeDefCall("lsh", methodType, DefBootstrap.SHIFT_OPERATOR, flags); - break; - case USH: - invokeDefCall("ush", methodType, DefBootstrap.SHIFT_OPERATOR, flags); - break; - case RSH: - invokeDefCall("rsh", methodType, DefBootstrap.SHIFT_OPERATOR, flags); - break; - case BWAND: - invokeDefCall("and", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case XOR: - invokeDefCall("xor", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - case BWOR: - invokeDefCall("or", methodType, DefBootstrap.BINARY_OPERATOR, flags); - break; - default: - throw location.createError(new IllegalStateException("Illegal tree structure.")); + } + case SUB -> invokeDefCall("sub", methodType, DefBootstrap.BINARY_OPERATOR, flags); + case LSH -> invokeDefCall("lsh", methodType, DefBootstrap.SHIFT_OPERATOR, flags); + case USH -> invokeDefCall("ush", methodType, DefBootstrap.SHIFT_OPERATOR, flags); + case RSH -> invokeDefCall("rsh", methodType, DefBootstrap.SHIFT_OPERATOR, flags); + case BWAND -> invokeDefCall("and", methodType, DefBootstrap.BINARY_OPERATOR, flags); + case XOR -> invokeDefCall("xor", methodType, DefBootstrap.BINARY_OPERATOR, flags); + case BWOR -> invokeDefCall("or", methodType, DefBootstrap.BINARY_OPERATOR, flags); + default -> throw location.createError(new IllegalStateException("Illegal tree structure.")); } } @@ -389,41 +368,18 @@ public void writeBinaryInstruction(Location location, Class clazz, Operation } switch (operation) { - case MUL: - math(GeneratorAdapter.MUL, getType(clazz)); - break; - case DIV: - math(GeneratorAdapter.DIV, getType(clazz)); - break; - case REM: - math(GeneratorAdapter.REM, getType(clazz)); - break; - case ADD: - math(GeneratorAdapter.ADD, getType(clazz)); - break; - case SUB: - math(GeneratorAdapter.SUB, getType(clazz)); - break; - case LSH: - math(GeneratorAdapter.SHL, getType(clazz)); - break; - case USH: - math(GeneratorAdapter.USHR, getType(clazz)); - break; - case RSH: - math(GeneratorAdapter.SHR, getType(clazz)); - break; - case BWAND: - math(GeneratorAdapter.AND, getType(clazz)); - break; - case XOR: - math(GeneratorAdapter.XOR, getType(clazz)); - break; - case BWOR: - math(GeneratorAdapter.OR, getType(clazz)); - break; - default: - throw location.createError(new IllegalStateException("Illegal tree structure.")); + case MUL -> math(GeneratorAdapter.MUL, getType(clazz)); + case DIV -> math(GeneratorAdapter.DIV, getType(clazz)); + case REM -> math(GeneratorAdapter.REM, getType(clazz)); + case ADD -> math(GeneratorAdapter.ADD, getType(clazz)); + case SUB -> math(GeneratorAdapter.SUB, getType(clazz)); + case LSH -> math(GeneratorAdapter.SHL, getType(clazz)); + case USH -> math(GeneratorAdapter.USHR, getType(clazz)); + case RSH -> math(GeneratorAdapter.SHR, getType(clazz)); + case BWAND -> math(GeneratorAdapter.AND, getType(clazz)); + case XOR -> math(GeneratorAdapter.XOR, getType(clazz)); + case BWOR -> math(GeneratorAdapter.OR, getType(clazz)); + default -> throw location.createError(new IllegalStateException("Illegal tree structure.")); } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/api/Json.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/api/Json.java index bed5b1fda43af..e51ed2e27065e 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/api/Json.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/api/Json.java @@ -27,20 +27,14 @@ public static Object load(String json) throws IOException { json ); - switch (parser.nextToken()) { - case START_ARRAY: - return parser.list(); - case START_OBJECT: - return parser.map(); - case VALUE_NUMBER: - return parser.numberValue(); - case VALUE_BOOLEAN: - return parser.booleanValue(); - case VALUE_STRING: - return parser.text(); - default: - return null; - } + return switch (parser.nextToken()) { + case START_ARRAY -> parser.list(); + case START_OBJECT -> parser.map(); + case VALUE_NUMBER -> parser.numberValue(); + case VALUE_BOOLEAN -> parser.booleanValue(); + case VALUE_STRING -> parser.text(); + default -> null; + }; } /** diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java index eee65f0e40b66..128b066728797 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java @@ -2282,34 +2282,17 @@ public void visitRegex(ERegex userRegexNode, SemanticScope semanticScope) { for (int i = 0; i < flags.length(); ++i) { char flag = flags.charAt(i); - switch (flag) { - case 'c': - regexFlags |= Pattern.CANON_EQ; - break; - case 'i': - regexFlags |= Pattern.CASE_INSENSITIVE; - break; - case 'l': - regexFlags |= Pattern.LITERAL; - break; - case 'm': - regexFlags |= Pattern.MULTILINE; - break; - case 's': - regexFlags |= Pattern.DOTALL; - break; - case 'U': - regexFlags |= Pattern.UNICODE_CHARACTER_CLASS; - break; - case 'u': - regexFlags |= Pattern.UNICODE_CASE; - break; - case 'x': - regexFlags |= Pattern.COMMENTS; - break; - default: - throw new IllegalArgumentException("invalid regular expression: unknown flag [" + flag + "]"); - } + regexFlags |= switch (flag) { + case 'c' -> Pattern.CANON_EQ; + case 'i' -> Pattern.CASE_INSENSITIVE; + case 'l' -> Pattern.LITERAL; + case 'm' -> Pattern.MULTILINE; + case 's' -> Pattern.DOTALL; + case 'U' -> Pattern.UNICODE_CHARACTER_CLASS; + case 'u' -> Pattern.UNICODE_CASE; + case 'x' -> Pattern.COMMENTS; + default -> throw new IllegalArgumentException("invalid regular expression: unknown flag [" + flag + "]"); + }; } Pattern compiled; diff --git a/modules/lang-painless/src/test/java/org/elasticsearch/painless/ListTests.java b/modules/lang-painless/src/test/java/org/elasticsearch/painless/ListTests.java index 96fa861c6e807..17e222357555e 100644 --- a/modules/lang-painless/src/test/java/org/elasticsearch/painless/ListTests.java +++ b/modules/lang-painless/src/test/java/org/elasticsearch/painless/ListTests.java @@ -31,22 +31,15 @@ protected String valueCtorCall(String valueType, int size) { } private String fillValue(String valueType) { - switch (valueType) { - case "int": - return "0"; - case "long": - return "0L"; - case "short": - return "(short) 0"; - case "byte": - return "(byte) 0"; - case "float": - return "0.0f"; - case "double": - return "0.0"; // Double is implicit for decimal constants - default: - return null; - } + return switch (valueType) { + case "int" -> "0"; + case "long" -> "0L"; + case "short" -> "(short) 0"; + case "byte" -> "(byte) 0"; + case "float" -> "0.0f"; + case "double" -> "0.0"; // Double is implicit for decimal constants + default -> null; + }; } @Override diff --git a/modules/lang-painless/src/test/java/org/elasticsearch/painless/action/PainlessExecuteResponseTests.java b/modules/lang-painless/src/test/java/org/elasticsearch/painless/action/PainlessExecuteResponseTests.java index 069fa5e56929b..6341cdeb2d2bb 100644 --- a/modules/lang-painless/src/test/java/org/elasticsearch/painless/action/PainlessExecuteResponseTests.java +++ b/modules/lang-painless/src/test/java/org/elasticsearch/painless/action/PainlessExecuteResponseTests.java @@ -22,20 +22,12 @@ protected Writeable.Reader instanceReader() { @Override protected PainlessExecuteAction.Response createTestInstance() { - Object result; - switch (randomIntBetween(0, 2)) { - case 0: - result = randomAlphaOfLength(10); - break; - case 1: - result = randomBoolean(); - break; - case 2: - result = randomDoubleBetween(-10, 10, true); - break; - default: - throw new IllegalStateException("invalid branch"); - } + Object result = switch (randomIntBetween(0, 2)) { + case 0 -> randomAlphaOfLength(10); + case 1 -> randomBoolean(); + case 2 -> randomDoubleBetween(-10, 10, true); + default -> throw new IllegalStateException("invalid branch"); + }; return new PainlessExecuteAction.Response(result); } @@ -44,20 +36,12 @@ protected PainlessExecuteAction.Response doParseInstance(XContentParser parser) parser.nextToken(); // START-OBJECT parser.nextToken(); // FIELD-NAME XContentParser.Token token = parser.nextToken(); // result value - Object result; - switch (token) { - case VALUE_STRING: - result = parser.text(); - break; - case VALUE_BOOLEAN: - result = parser.booleanValue(); - break; - case VALUE_NUMBER: - result = parser.doubleValue(); - break; - default: - throw new IOException("invalid response"); - } + Object result = switch (token) { + case VALUE_STRING -> parser.text(); + case VALUE_BOOLEAN -> parser.booleanValue(); + case VALUE_NUMBER -> parser.doubleValue(); + default -> throw new IOException("invalid response"); + }; return new PainlessExecuteAction.Response(result); } } diff --git a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java index d8f7b346ffae6..4a45c176733f4 100644 --- a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java +++ b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java @@ -112,15 +112,11 @@ public static class Defaults { public static final double DISTANCE_ERROR_PCT = 0.025d; public static int defaultTreeLevel(String tree) { - switch (tree) { - case PrefixTrees.GEOHASH: - return GEOHASH_TREE_LEVELS; - case PrefixTrees.LEGACY_QUADTREE: - case PrefixTrees.QUADTREE: - return QUADTREE_LEVELS; - default: - throw new IllegalArgumentException("Unknown prefix type [" + tree + "]"); - } + return switch (tree) { + case PrefixTrees.GEOHASH -> GEOHASH_TREE_LEVELS; + case PrefixTrees.LEGACY_QUADTREE, PrefixTrees.QUADTREE -> QUADTREE_LEVELS; + default -> throw new IllegalArgumentException("Unknown prefix type [" + tree + "]"); + }; } } diff --git a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java index 6509619ffbf8f..805ed8a65597a 100644 --- a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java +++ b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java @@ -102,26 +102,17 @@ private GeoWKTParser() {} throw new ElasticsearchParseException("Expected geometry type [{}] but found [{}]", shapeType, type); } } - switch (type) { - case POINT: - return parsePoint(stream, ignoreZValue, coerce); - case MULTIPOINT: - return parseMultiPoint(stream, ignoreZValue, coerce); - case LINESTRING: - return parseLine(stream, ignoreZValue, coerce); - case MULTILINESTRING: - return parseMultiLine(stream, ignoreZValue, coerce); - case POLYGON: - return parsePolygon(stream, ignoreZValue, coerce); - case MULTIPOLYGON: - return parseMultiPolygon(stream, ignoreZValue, coerce); - case ENVELOPE: - return parseBBox(stream); - case GEOMETRYCOLLECTION: - return parseGeometryCollection(stream, ignoreZValue, coerce); - default: - throw new IllegalArgumentException("Unknown geometry type: " + type); - } + return switch (type) { + case POINT -> parsePoint(stream, ignoreZValue, coerce); + case MULTIPOINT -> parseMultiPoint(stream, ignoreZValue, coerce); + case LINESTRING -> parseLine(stream, ignoreZValue, coerce); + case MULTILINESTRING -> parseMultiLine(stream, ignoreZValue, coerce); + case POLYGON -> parsePolygon(stream, ignoreZValue, coerce); + case MULTIPOLYGON -> parseMultiPolygon(stream, ignoreZValue, coerce); + case ENVELOPE -> parseBBox(stream); + case GEOMETRYCOLLECTION -> parseGeometryCollection(stream, ignoreZValue, coerce); + default -> throw new IllegalArgumentException("Unknown geometry type: " + type); + }; } private static EnvelopeBuilder parseBBox(StreamTokenizer stream) throws IOException, ElasticsearchParseException { @@ -317,17 +308,13 @@ private static double nextNumber(StreamTokenizer stream) throws IOException, Ela } private static String tokenString(StreamTokenizer stream) { - switch (stream.ttype) { - case StreamTokenizer.TT_WORD: - return stream.sval; - case StreamTokenizer.TT_EOF: - return EOF; - case StreamTokenizer.TT_EOL: - return EOL; - case StreamTokenizer.TT_NUMBER: - return NUMBER; - } - return "'" + (char) stream.ttype + "'"; + return switch (stream.ttype) { + case StreamTokenizer.TT_WORD -> stream.sval; + case StreamTokenizer.TT_EOF -> EOF; + case StreamTokenizer.TT_EOL -> EOL; + case StreamTokenizer.TT_NUMBER -> NUMBER; + default -> "'" + (char) stream.ttype + "'"; + }; } private static boolean isNumberNext(StreamTokenizer stream) throws IOException { diff --git a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/query/LegacyGeoShapeQueryProcessor.java b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/query/LegacyGeoShapeQueryProcessor.java index 5ea5c76fbcf3f..cad709358a19e 100644 --- a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/query/LegacyGeoShapeQueryProcessor.java +++ b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/query/LegacyGeoShapeQueryProcessor.java @@ -97,18 +97,12 @@ public Query geoShapeQuery( } public static SpatialArgs getArgs(Geometry shape, ShapeRelation relation) { - switch (relation) { - case DISJOINT: - return new SpatialArgs(SpatialOperation.IsDisjointTo, buildS4J(shape)); - case INTERSECTS: - return new SpatialArgs(SpatialOperation.Intersects, buildS4J(shape)); - case WITHIN: - return new SpatialArgs(SpatialOperation.IsWithin, buildS4J(shape)); - case CONTAINS: - return new SpatialArgs(SpatialOperation.Contains, buildS4J(shape)); - default: - throw new IllegalArgumentException("invalid relation [" + relation + "]"); - } + return switch (relation) { + case DISJOINT -> new SpatialArgs(SpatialOperation.IsDisjointTo, buildS4J(shape)); + case INTERSECTS -> new SpatialArgs(SpatialOperation.Intersects, buildS4J(shape)); + case WITHIN -> new SpatialArgs(SpatialOperation.IsWithin, buildS4J(shape)); + case CONTAINS -> new SpatialArgs(SpatialOperation.Contains, buildS4J(shape)); + }; } /** diff --git a/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/EnvelopeBuilderTests.java b/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/EnvelopeBuilderTests.java index 65b4dcefca26d..28fc05eca424d 100644 --- a/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/EnvelopeBuilderTests.java +++ b/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/EnvelopeBuilderTests.java @@ -35,35 +35,27 @@ protected EnvelopeBuilder createMutation(EnvelopeBuilder original) throws IOExce } static EnvelopeBuilder mutate(EnvelopeBuilder original) throws IOException { - EnvelopeBuilder mutation = copyShape(original); + copyShape(original); // move one corner to the middle of original - switch (randomIntBetween(0, 3)) { - case 0: - mutation = new EnvelopeBuilder( - new Coordinate(randomDoubleBetween(-180.0, original.bottomRight().x, true), original.topLeft().y), - original.bottomRight() - ); - break; - case 1: - mutation = new EnvelopeBuilder( - new Coordinate(original.topLeft().x, randomDoubleBetween(original.bottomRight().y, 90.0, true)), - original.bottomRight() - ); - break; - case 2: - mutation = new EnvelopeBuilder( - original.topLeft(), - new Coordinate(randomDoubleBetween(original.topLeft().x, 180.0, true), original.bottomRight().y) - ); - break; - case 3: - mutation = new EnvelopeBuilder( - original.topLeft(), - new Coordinate(original.bottomRight().x, randomDoubleBetween(-90.0, original.topLeft().y, true)) - ); - break; - } - return mutation; + return switch (randomIntBetween(0, 3)) { + case 0 -> new EnvelopeBuilder( + new Coordinate(randomDoubleBetween(-180.0, original.bottomRight().x, true), original.topLeft().y), + original.bottomRight() + ); + case 1 -> new EnvelopeBuilder( + new Coordinate(original.topLeft().x, randomDoubleBetween(original.bottomRight().y, 90.0, true)), + original.bottomRight() + ); + case 2 -> new EnvelopeBuilder( + original.topLeft(), + new Coordinate(randomDoubleBetween(original.topLeft().x, 180.0, true), original.bottomRight().y) + ); + case 3 -> new EnvelopeBuilder( + original.topLeft(), + new Coordinate(original.bottomRight().x, randomDoubleBetween(-90.0, original.topLeft().y, true)) + ); + default -> copyShape(original); + }; } static EnvelopeBuilder createRandomShape() { diff --git a/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/GeometryCollectionBuilderTests.java b/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/GeometryCollectionBuilderTests.java index 3989eb75df571..8f2c498f55fa0 100644 --- a/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/GeometryCollectionBuilderTests.java +++ b/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/GeometryCollectionBuilderTests.java @@ -20,30 +20,14 @@ protected GeometryCollectionBuilder createTestShapeBuilder() { int shapes = randomIntBetween(0, 8); for (int i = 0; i < shapes; i++) { switch (randomIntBetween(0, 7)) { - case 0: - geometryCollection.shape(PointBuilderTests.createRandomShape()); - break; - case 1: - geometryCollection.shape(CircleBuilderTests.createRandomShape()); - break; - case 2: - geometryCollection.shape(EnvelopeBuilderTests.createRandomShape()); - break; - case 3: - geometryCollection.shape(LineStringBuilderTests.createRandomShape()); - break; - case 4: - geometryCollection.shape(MultiLineStringBuilderTests.createRandomShape()); - break; - case 5: - geometryCollection.shape(MultiPolygonBuilderTests.createRandomShape()); - break; - case 6: - geometryCollection.shape(MultiPointBuilderTests.createRandomShape()); - break; - case 7: - geometryCollection.shape(PolygonBuilderTests.createRandomShape()); - break; + case 0 -> geometryCollection.shape(PointBuilderTests.createRandomShape()); + case 1 -> geometryCollection.shape(CircleBuilderTests.createRandomShape()); + case 2 -> geometryCollection.shape(EnvelopeBuilderTests.createRandomShape()); + case 3 -> geometryCollection.shape(LineStringBuilderTests.createRandomShape()); + case 4 -> geometryCollection.shape(MultiLineStringBuilderTests.createRandomShape()); + case 5 -> geometryCollection.shape(MultiPolygonBuilderTests.createRandomShape()); + case 6 -> geometryCollection.shape(MultiPointBuilderTests.createRandomShape()); + case 7 -> geometryCollection.shape(PolygonBuilderTests.createRandomShape()); } } return geometryCollection; @@ -59,35 +43,19 @@ static GeometryCollectionBuilder mutate(GeometryCollectionBuilder original) thro if (mutation.shapes.size() > 0) { int shapePosition = randomIntBetween(0, mutation.shapes.size() - 1); ShapeBuilder shapeToChange = mutation.shapes.get(shapePosition); - switch (shapeToChange.type()) { - case POINT: - shapeToChange = PointBuilderTests.mutate((PointBuilder) shapeToChange); - break; - case CIRCLE: - shapeToChange = CircleBuilderTests.mutate((CircleBuilder) shapeToChange); - break; - case ENVELOPE: - shapeToChange = EnvelopeBuilderTests.mutate((EnvelopeBuilder) shapeToChange); - break; - case LINESTRING: - shapeToChange = LineStringBuilderTests.mutate((LineStringBuilder) shapeToChange); - break; - case MULTILINESTRING: - shapeToChange = MultiLineStringBuilderTests.mutate((MultiLineStringBuilder) shapeToChange); - break; - case MULTIPOLYGON: - shapeToChange = MultiPolygonBuilderTests.mutate((MultiPolygonBuilder) shapeToChange); - break; - case MULTIPOINT: - shapeToChange = MultiPointBuilderTests.mutate((MultiPointBuilder) shapeToChange); - break; - case POLYGON: - shapeToChange = PolygonBuilderTests.mutate((PolygonBuilder) shapeToChange); - break; - case GEOMETRYCOLLECTION: - throw new UnsupportedOperationException("GeometryCollection should not be nested inside each other"); - } - mutation.shapes.set(shapePosition, shapeToChange); + mutation.shapes.set(shapePosition, switch (shapeToChange.type()) { + case POINT -> PointBuilderTests.mutate((PointBuilder) shapeToChange); + case CIRCLE -> CircleBuilderTests.mutate((CircleBuilder) shapeToChange); + case ENVELOPE -> EnvelopeBuilderTests.mutate((EnvelopeBuilder) shapeToChange); + case LINESTRING -> LineStringBuilderTests.mutate((LineStringBuilder) shapeToChange); + case MULTILINESTRING -> MultiLineStringBuilderTests.mutate((MultiLineStringBuilder) shapeToChange); + case MULTIPOLYGON -> MultiPolygonBuilderTests.mutate((MultiPolygonBuilder) shapeToChange); + case MULTIPOINT -> MultiPointBuilderTests.mutate((MultiPointBuilder) shapeToChange); + case POLYGON -> PolygonBuilderTests.mutate((PolygonBuilder) shapeToChange); + case GEOMETRYCOLLECTION -> throw new UnsupportedOperationException( + "GeometryCollection should not be nested inside each other" + ); + }); } else { mutation.shape(RandomShapeGenerator.createShape(random())); } diff --git a/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java b/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java index 7e2cd439d009a..93115a3af6c86 100644 --- a/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java +++ b/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java @@ -290,18 +290,13 @@ Query toQuery(String field, String feature, boolean positiveScoreImpact) { private static ScoreFunction readScoreFunction(StreamInput in) throws IOException { byte b = in.readByte(); - switch (b) { - case 0: - return new ScoreFunction.Log(in); - case 1: - return new ScoreFunction.Saturation(in); - case 2: - return new ScoreFunction.Sigmoid(in); - case 3: - return new ScoreFunction.Linear(in); - default: - throw new IOException("Illegal score function id: " + b); - } + return switch (b) { + case 0 -> new ScoreFunction.Log(in); + case 1 -> new ScoreFunction.Saturation(in); + case 2 -> new ScoreFunction.Sigmoid(in); + case 3 -> new ScoreFunction.Linear(in); + default -> throw new IOException("Illegal score function id: " + b); + }; } public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("feature", args -> { diff --git a/modules/mapper-extras/src/test/java/org/elasticsearch/index/mapper/extras/ScaledFloatFieldMapperTests.java b/modules/mapper-extras/src/test/java/org/elasticsearch/index/mapper/extras/ScaledFloatFieldMapperTests.java index 75042060940eb..6dc79f82bd876 100644 --- a/modules/mapper-extras/src/test/java/org/elasticsearch/index/mapper/extras/ScaledFloatFieldMapperTests.java +++ b/modules/mapper-extras/src/test/java/org/elasticsearch/index/mapper/extras/ScaledFloatFieldMapperTests.java @@ -350,17 +350,12 @@ protected Object generateRandomInputValue(MappedFieldType ft) { * range of valid values. */ double v = randomDoubleBetween(-Float.MAX_VALUE, Float.MAX_VALUE, true); - switch (between(0, 3)) { - case 0: - return v; - case 1: - return (float) v; - case 2: - return Double.toString(v); - case 3: - return Float.toString((float) v); - default: - throw new IllegalArgumentException(); - } + return switch (between(0, 3)) { + case 0 -> v; + case 1 -> (float) v; + case 2 -> Double.toString(v); + case 3 -> Float.toString((float) v); + default -> throw new IllegalArgumentException(); + }; } } diff --git a/modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorFieldMapperTests.java b/modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorFieldMapperTests.java index cb6a870508ce0..f789d8c2c2a03 100644 --- a/modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorFieldMapperTests.java +++ b/modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorFieldMapperTests.java @@ -939,31 +939,29 @@ public void testEncodeRange() { final int randomFrom = randomInt(); final byte[] encodedFrom; switch (encodingType) { - case 0: + case 0 -> { encodedFrom = new byte[Integer.BYTES]; IntPoint.encodeDimension(randomFrom, encodedFrom, 0); - break; - case 1: + } + case 1 -> { encodedFrom = new byte[Long.BYTES]; LongPoint.encodeDimension(randomFrom, encodedFrom, 0); - break; - default: - throw new AssertionError("unexpected encoding type [" + encodingType + "]"); + } + default -> throw new AssertionError("unexpected encoding type [" + encodingType + "]"); } final int randomTo = randomIntBetween(randomFrom, Integer.MAX_VALUE); final byte[] encodedTo; switch (encodingType) { - case 0: + case 0 -> { encodedTo = new byte[Integer.BYTES]; IntPoint.encodeDimension(randomTo, encodedTo, 0); - break; - case 1: + } + case 1 -> { encodedTo = new byte[Long.BYTES]; LongPoint.encodeDimension(randomTo, encodedTo, 0); - break; - default: - throw new AssertionError("unexpected encoding type [" + encodingType + "]"); + } + default -> throw new AssertionError("unexpected encoding type [" + encodingType + "]"); } String randomFieldName = randomAlphaOfLength(5); @@ -975,20 +973,19 @@ public void testEncodeRange() { MurmurHash3.hash128(fieldAsBytesRef.bytes, fieldAsBytesRef.offset, fieldAsBytesRef.length, 0, hash); switch (encodingType) { - case 0: + case 0 -> { assertEquals(hash.h1, ByteBuffer.wrap(subByteArray(result, 0, 8)).getLong()); assertEquals(randomFrom, IntPoint.decodeDimension(subByteArray(result, 12, 4), 0)); assertEquals(hash.h1, ByteBuffer.wrap(subByteArray(result, 16, 8)).getLong()); assertEquals(randomTo, IntPoint.decodeDimension(subByteArray(result, 28, 4), 0)); - break; - case 1: + } + case 1 -> { assertEquals(hash.h1, ByteBuffer.wrap(subByteArray(result, 0, 8)).getLong()); assertEquals(randomFrom, LongPoint.decodeDimension(subByteArray(result, 8, 8), 0)); assertEquals(hash.h1, ByteBuffer.wrap(subByteArray(result, 16, 8)).getLong()); assertEquals(randomTo, LongPoint.decodeDimension(subByteArray(result, 24, 8), 0)); - break; - default: - throw new AssertionError("unexpected encoding type [" + encodingType + "]"); + } + default -> throw new AssertionError("unexpected encoding type [" + encodingType + "]"); } } } diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/DiscountedCumulativeGainTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/DiscountedCumulativeGainTests.java index d415946530e7c..62fd56664ee33 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/DiscountedCumulativeGainTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/DiscountedCumulativeGainTests.java @@ -319,23 +319,19 @@ public void testEqualsAndHash() throws IOException { } private static DiscountedCumulativeGain mutateTestItem(DiscountedCumulativeGain original) { - switch (randomIntBetween(0, 2)) { - case 0: - return new DiscountedCumulativeGain(original.getNormalize() == false, original.getUnknownDocRating(), original.getK()); - case 1: - return new DiscountedCumulativeGain( - original.getNormalize(), - randomValueOtherThan(original.getUnknownDocRating(), () -> randomIntBetween(0, 10)), - original.getK() - ); - case 2: - return new DiscountedCumulativeGain( - original.getNormalize(), - original.getUnknownDocRating(), - randomValueOtherThan(original.getK(), () -> randomIntBetween(1, 10)) - ); - default: - throw new IllegalArgumentException("mutation variant not allowed"); - } + return switch (randomIntBetween(0, 2)) { + case 0 -> new DiscountedCumulativeGain(original.getNormalize() == false, original.getUnknownDocRating(), original.getK()); + case 1 -> new DiscountedCumulativeGain( + original.getNormalize(), + randomValueOtherThan(original.getUnknownDocRating(), () -> randomIntBetween(0, 10)), + original.getK() + ); + case 2 -> new DiscountedCumulativeGain( + original.getNormalize(), + original.getUnknownDocRating(), + randomValueOtherThan(original.getK(), () -> randomIntBetween(1, 10)) + ); + default -> throw new IllegalArgumentException("mutation variant not allowed"); + }; } } diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/EvalQueryQualityTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/EvalQueryQualityTests.java index ef69287e36f9f..77b0edaec8fb3 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/EvalQueryQualityTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/EvalQueryQualityTests.java @@ -52,23 +52,16 @@ public static EvalQueryQuality randomEvalQueryQuality() { if (randomBoolean()) { int metricDetail = randomIntBetween(0, 2); switch (metricDetail) { - case 0: - evalQueryQuality.setMetricDetails(new PrecisionAtK.Detail(randomIntBetween(0, 1000), randomIntBetween(0, 1000))); - break; - case 1: - evalQueryQuality.setMetricDetails(new MeanReciprocalRank.Detail(randomIntBetween(0, 1000))); - break; - case 2: - evalQueryQuality.setMetricDetails( - new DiscountedCumulativeGain.Detail( - randomDoubleBetween(0, 1, true), - randomBoolean() ? randomDoubleBetween(0, 1, true) : 0, - randomInt() - ) - ); - break; - default: - throw new IllegalArgumentException("illegal randomized value in test"); + case 0 -> evalQueryQuality.setMetricDetails(new PrecisionAtK.Detail(randomIntBetween(0, 1000), randomIntBetween(0, 1000))); + case 1 -> evalQueryQuality.setMetricDetails(new MeanReciprocalRank.Detail(randomIntBetween(0, 1000))); + case 2 -> evalQueryQuality.setMetricDetails( + new DiscountedCumulativeGain.Detail( + randomDoubleBetween(0, 1, true), + randomBoolean() ? randomDoubleBetween(0, 1, true) : 0, + randomInt() + ) + ); + default -> throw new IllegalArgumentException("illegal randomized value in test"); } } evalQueryQuality.addHitsAndRatings(ratedHits); diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/ExpectedReciprocalRankTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/ExpectedReciprocalRankTests.java index 5a95d8813b16f..3cb873b4c22ff 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/ExpectedReciprocalRankTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/ExpectedReciprocalRankTests.java @@ -196,23 +196,19 @@ public void testEqualsAndHash() throws IOException { } private static ExpectedReciprocalRank mutateTestItem(ExpectedReciprocalRank original) { - switch (randomIntBetween(0, 2)) { - case 0: - return new ExpectedReciprocalRank(original.getMaxRelevance() + 1, original.getUnknownDocRating(), original.getK()); - case 1: - return new ExpectedReciprocalRank( - original.getMaxRelevance(), - randomValueOtherThan(original.getUnknownDocRating(), () -> randomIntBetween(0, 10)), - original.getK() - ); - case 2: - return new ExpectedReciprocalRank( - original.getMaxRelevance(), - original.getUnknownDocRating(), - randomValueOtherThan(original.getK(), () -> randomIntBetween(1, 10)) - ); - default: - throw new IllegalArgumentException("mutation variant not allowed"); - } + return switch (randomIntBetween(0, 2)) { + case 0 -> new ExpectedReciprocalRank(original.getMaxRelevance() + 1, original.getUnknownDocRating(), original.getK()); + case 1 -> new ExpectedReciprocalRank( + original.getMaxRelevance(), + randomValueOtherThan(original.getUnknownDocRating(), () -> randomIntBetween(0, 10)), + original.getK() + ); + case 2 -> new ExpectedReciprocalRank( + original.getMaxRelevance(), + original.getUnknownDocRating(), + randomValueOtherThan(original.getK(), () -> randomIntBetween(1, 10)) + ); + default -> throw new IllegalArgumentException("mutation variant not allowed"); + }; } } diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/PrecisionAtKTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/PrecisionAtKTests.java index b82690ea74211..092aafbe2b484 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/PrecisionAtKTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/PrecisionAtKTests.java @@ -224,32 +224,24 @@ private static PrecisionAtK copy(PrecisionAtK original) { } private static PrecisionAtK mutate(PrecisionAtK original) { - PrecisionAtK pAtK; - switch (randomIntBetween(0, 2)) { - case 0: - pAtK = new PrecisionAtK( - original.getRelevantRatingThreshold(), - original.getIgnoreUnlabeled() == false, - original.forcedSearchSize().getAsInt() - ); - break; - case 1: - pAtK = new PrecisionAtK( - randomValueOtherThan(original.getRelevantRatingThreshold(), () -> randomIntBetween(0, 10)), - original.getIgnoreUnlabeled(), - original.forcedSearchSize().getAsInt() - ); - break; - case 2: - pAtK = new PrecisionAtK( - original.getRelevantRatingThreshold(), - original.getIgnoreUnlabeled(), - original.forcedSearchSize().getAsInt() + 1 - ); - break; - default: - throw new IllegalStateException("The test should only allow three parameters mutated"); - } + PrecisionAtK pAtK = switch (randomIntBetween(0, 2)) { + case 0 -> new PrecisionAtK( + original.getRelevantRatingThreshold(), + original.getIgnoreUnlabeled() == false, + original.forcedSearchSize().getAsInt() + ); + case 1 -> new PrecisionAtK( + randomValueOtherThan(original.getRelevantRatingThreshold(), () -> randomIntBetween(0, 10)), + original.getIgnoreUnlabeled(), + original.forcedSearchSize().getAsInt() + ); + case 2 -> new PrecisionAtK( + original.getRelevantRatingThreshold(), + original.getIgnoreUnlabeled(), + original.forcedSearchSize().getAsInt() + 1 + ); + default -> throw new IllegalStateException("The test should only allow three parameters mutated"); + }; return pAtK; } diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedDocumentTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedDocumentTests.java index c3e33d0e77e56..d65cacde56994 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedDocumentTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedDocumentTests.java @@ -80,17 +80,10 @@ private static RatedDocument mutateTestItem(RatedDocument original) { String docId = original.getDocID(); switch (randomIntBetween(0, 2)) { - case 0: - rating = randomValueOtherThan(rating, () -> randomInt()); - break; - case 1: - index = randomValueOtherThan(index, () -> randomAlphaOfLength(10)); - break; - case 2: - docId = randomValueOtherThan(docId, () -> randomAlphaOfLength(10)); - break; - default: - throw new IllegalStateException("The test should only allow two parameters mutated"); + case 0 -> rating = randomValueOtherThan(rating, () -> randomInt()); + case 1 -> index = randomValueOtherThan(index, () -> randomAlphaOfLength(10)); + case 2 -> docId = randomValueOtherThan(docId, () -> randomAlphaOfLength(10)); + default -> throw new IllegalStateException("The test should only allow two parameters mutated"); } return new RatedDocument(index, docId, rating); } diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedSearchHitTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedSearchHitTests.java index d303dea49b1f6..d441c96cb4328 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedSearchHitTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedSearchHitTests.java @@ -40,14 +40,14 @@ private static RatedSearchHit mutateTestItem(RatedSearchHit original) { OptionalInt rating = original.getRating(); SearchHit hit = original.getSearchHit(); switch (randomIntBetween(0, 1)) { - case 0: - rating = rating.isPresent() ? OptionalInt.of(rating.getAsInt() + 1) : OptionalInt.of(randomInt(5)); - break; - case 1: - hit = new SearchHit(hit.docId(), hit.getId() + randomAlphaOfLength(10), Collections.emptyMap(), Collections.emptyMap()); - break; - default: - throw new IllegalStateException("The test should only allow two parameters mutated"); + case 0 -> rating = rating.isPresent() ? OptionalInt.of(rating.getAsInt() + 1) : OptionalInt.of(randomInt(5)); + case 1 -> hit = new SearchHit( + hit.docId(), + hit.getId() + randomAlphaOfLength(10), + Collections.emptyMap(), + Collections.emptyMap() + ); + default -> throw new IllegalStateException("The test should only allow two parameters mutated"); } return new RatedSearchHit(hit, rating); } diff --git a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RecallAtKTests.java b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RecallAtKTests.java index ced3bb12ea1d6..d021b0a6037e6 100644 --- a/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RecallAtKTests.java +++ b/modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RecallAtKTests.java @@ -202,20 +202,14 @@ private static RecallAtK copy(RecallAtK original) { } private static RecallAtK mutate(RecallAtK original) { - RecallAtK recallAtK; - switch (randomIntBetween(0, 1)) { - case 0: - recallAtK = new RecallAtK( - randomValueOtherThan(original.getRelevantRatingThreshold(), () -> randomIntBetween(0, 10)), - original.forcedSearchSize().getAsInt() - ); - break; - case 1: - recallAtK = new RecallAtK(original.getRelevantRatingThreshold(), original.forcedSearchSize().getAsInt() + 1); - break; - default: - throw new IllegalStateException("The test should only allow two parameters mutated"); - } + RecallAtK recallAtK = switch (randomIntBetween(0, 1)) { + case 0 -> new RecallAtK( + randomValueOtherThan(original.getRelevantRatingThreshold(), () -> randomIntBetween(0, 10)), + original.forcedSearchSize().getAsInt() + ); + case 1 -> new RecallAtK(original.getRelevantRatingThreshold(), original.forcedSearchSize().getAsInt() + 1); + default -> throw new IllegalStateException("The test should only allow two parameters mutated"); + }; return recallAtK; } diff --git a/modules/reindex/src/main/java/org/elasticsearch/reindex/AbstractAsyncBulkByScrollAction.java b/modules/reindex/src/main/java/org/elasticsearch/reindex/AbstractAsyncBulkByScrollAction.java index 94f54d4a5c70f..16f0c61c8e673 100644 --- a/modules/reindex/src/main/java/org/elasticsearch/reindex/AbstractAsyncBulkByScrollAction.java +++ b/modules/reindex/src/main/java/org/elasticsearch/reindex/AbstractAsyncBulkByScrollAction.java @@ -908,17 +908,20 @@ public RequestWrapper apply(RequestWrapper request, ScrollableHitSource.Hi protected RequestWrapper scriptChangedOpType(RequestWrapper request, OpType oldOpType, OpType newOpType) { switch (newOpType) { - case NOOP: + case NOOP -> { taskWorker.countNoop(); return null; - case DELETE: + } + case DELETE -> { RequestWrapper delete = wrap(new DeleteRequest(request.getIndex(), request.getId())); delete.setVersion(request.getVersion()); delete.setVersionType(VersionType.INTERNAL); delete.setRouting(request.getRouting()); return delete; - default: - throw new IllegalArgumentException("Unsupported operation type change from [" + oldOpType + "] to [" + newOpType + "]"); + } + default -> throw new IllegalArgumentException( + "Unsupported operation type change from [" + oldOpType + "] to [" + newOpType + "]" + ); } } @@ -946,18 +949,14 @@ public enum OpType { public static OpType fromString(String opType) { String lowerOpType = opType.toLowerCase(Locale.ROOT); - switch (lowerOpType) { - case "noop": - return OpType.NOOP; - case "index": - return OpType.INDEX; - case "delete": - return OpType.DELETE; - default: - throw new IllegalArgumentException( - "Operation type [" + lowerOpType + "] not allowed, only " + Arrays.toString(values()) + " are allowed" - ); - } + return switch (lowerOpType) { + case "noop" -> OpType.NOOP; + case "index" -> OpType.INDEX; + case "delete" -> OpType.DELETE; + default -> throw new IllegalArgumentException( + "Operation type [" + lowerOpType + "] not allowed, only " + Arrays.toString(values()) + " are allowed" + ); + }; } @Override diff --git a/modules/reindex/src/main/java/org/elasticsearch/reindex/Reindexer.java b/modules/reindex/src/main/java/org/elasticsearch/reindex/Reindexer.java index b73f61f3de426..80a2817a9dae4 100644 --- a/modules/reindex/src/main/java/org/elasticsearch/reindex/Reindexer.java +++ b/modules/reindex/src/main/java/org/elasticsearch/reindex/Reindexer.java @@ -336,14 +336,9 @@ protected void copyRouting(RequestWrapper request, String routing) { return; } switch (routingSpec) { - case "keep": - super.copyRouting(request, routing); - break; - case "discard": - super.copyRouting(request, null); - break; - default: - throw new IllegalArgumentException("Unsupported routing command"); + case "keep" -> super.copyRouting(request, routing); + case "discard" -> super.copyRouting(request, null); + default -> throw new IllegalArgumentException("Unsupported routing command"); } } diff --git a/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java b/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java index 0cf6c5d501f1e..57e983abbc57f 100644 --- a/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java +++ b/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java @@ -308,23 +308,22 @@ public void testBulkResponseSetsLotsOfStatus() throws Exception { boolean createdResponse; DocWriteRequest.OpType opType; switch (randomIntBetween(0, 2)) { - case 0: + case 0 -> { createdResponse = true; opType = DocWriteRequest.OpType.CREATE; created++; - break; - case 1: + } + case 1 -> { createdResponse = false; opType = randomFrom(DocWriteRequest.OpType.INDEX, DocWriteRequest.OpType.UPDATE); updated++; - break; - case 2: + } + case 2 -> { createdResponse = false; opType = DocWriteRequest.OpType.DELETE; deleted++; - break; - default: - throw new RuntimeException("Bad scenario"); + } + default -> throw new RuntimeException("Bad scenario"); } final int seqNo = randomInt(20); final int primaryTerm = randomIntBetween(1, 16); @@ -1146,15 +1145,18 @@ private Exception wrappedRejectedException() { int wraps = randomIntBetween(0, 4); for (int i = 0; i < wraps; i++) { switch (randomIntBetween(0, 2)) { - case 0: + case 0 -> { e = new SearchPhaseExecutionException("test", "test failure", e, new ShardSearchFailure[0]); continue; - case 1: + } + case 1 -> { e = new ReduceSearchPhaseException("test", "test failure", e, new ShardSearchFailure[0]); continue; - case 2: + } + case 2 -> { e = new ElasticsearchException(e); continue; + } } } return e; diff --git a/plugins/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureStorageService.java b/plugins/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureStorageService.java index 529d9f42a5e5b..e29eae4cb7b62 100644 --- a/plugins/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureStorageService.java +++ b/plugins/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureStorageService.java @@ -107,14 +107,11 @@ private static ProxyOptions getProxyOptions(AzureStorageSettings settings) { return null; } - switch (proxy.type()) { - case HTTP: - return new ProxyOptions(ProxyOptions.Type.HTTP, (InetSocketAddress) proxy.address()); - case SOCKS: - return new ProxyOptions(ProxyOptions.Type.SOCKS5, (InetSocketAddress) proxy.address()); - default: - return null; - } + return switch (proxy.type()) { + case HTTP -> new ProxyOptions(ProxyOptions.Type.HTTP, (InetSocketAddress) proxy.address()); + case SOCKS -> new ProxyOptions(ProxyOptions.Type.SOCKS5, (InetSocketAddress) proxy.address()); + default -> null; + }; } // non-static, package private for testing @@ -138,22 +135,11 @@ RequestRetryOptions getRetryOptions(LocationMode locationMode, AzureStorageSetti throw new IllegalArgumentException("Unable to use " + locationMode + " location mode without a secondary location URI"); } - final String secondaryHost; - switch (locationMode) { - case PRIMARY_ONLY: - case SECONDARY_ONLY: - secondaryHost = null; - break; - case PRIMARY_THEN_SECONDARY: - secondaryHost = secondaryUri; - break; - case SECONDARY_THEN_PRIMARY: - secondaryHost = primaryUri; - break; - default: - assert false; - throw new AssertionError("Impossible to get here"); - } + final String secondaryHost = switch (locationMode) { + case PRIMARY_ONLY, SECONDARY_ONLY -> null; + case PRIMARY_THEN_SECONDARY -> secondaryUri; + case SECONDARY_THEN_PRIMARY -> primaryUri; + }; // The request retry policy uses seconds as the default time unit, since // it's possible to configure a timeout < 1s we should ceil that value diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java index bdac50050c5bd..fb3586c040b87 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java @@ -433,23 +433,10 @@ private void assertPasswordProtectedKeystore() { private void verifyKeystorePermissions() { Path keystore = installation.config("elasticsearch.keystore"); switch (distribution.packaging) { - case TAR: - case ZIP: - assertThat(keystore, file(File, ARCHIVE_OWNER, ARCHIVE_OWNER, p660)); - break; - case DEB: - case RPM: - assertThat(keystore, file(File, "root", "elasticsearch", p660)); - break; - case DOCKER: - case DOCKER_UBI: - case DOCKER_IRON_BANK: - case DOCKER_CLOUD: - case DOCKER_CLOUD_ESS: - assertThat(keystore, DockerFileMatcher.file(p660)); - break; - default: - throw new IllegalStateException("Unknown Elasticsearch packaging type."); + case TAR, ZIP -> assertThat(keystore, file(File, ARCHIVE_OWNER, ARCHIVE_OWNER, p660)); + case DEB, RPM -> assertThat(keystore, file(File, "root", "elasticsearch", p660)); + case DOCKER, DOCKER_UBI, DOCKER_IRON_BANK, DOCKER_CLOUD, DOCKER_CLOUD_ESS -> assertThat(keystore, DockerFileMatcher.file(p660)); + default -> throw new IllegalStateException("Unknown Elasticsearch packaging type."); } } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java index 0247a3c6ae41a..63faaff327b4f 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java @@ -232,26 +232,19 @@ protected static Distribution distribution() { protected static void install() throws Exception { switch (distribution.packaging) { - case TAR: - case ZIP: + case TAR, ZIP -> { installation = Archives.installArchive(sh, distribution); Archives.verifyArchiveInstallation(installation, distribution); - break; - case DEB: - case RPM: + } + case DEB, RPM -> { installation = Packages.installPackage(sh, distribution); Packages.verifyPackageInstallation(installation, distribution, sh); - break; - case DOCKER: - case DOCKER_UBI: - case DOCKER_IRON_BANK: - case DOCKER_CLOUD: - case DOCKER_CLOUD_ESS: + } + case DOCKER, DOCKER_UBI, DOCKER_IRON_BANK, DOCKER_CLOUD, DOCKER_CLOUD_ESS -> { installation = Docker.runContainer(distribution); Docker.verifyContainerInstallation(installation); - break; - default: - throw new IllegalStateException("Unknown Elasticsearch packaging type."); + } + default -> throw new IllegalStateException("Unknown Elasticsearch packaging type."); } // the purpose of the packaging tests are not to all test auto heap, so we explicitly set heap size to 1g @@ -364,23 +357,10 @@ public void stopElasticsearch() throws Exception { public void awaitElasticsearchStartup(Shell.Result result) throws Exception { assertThat("Startup command should succeed. Stderr: [" + result + "]", result.exitCode, equalTo(0)); switch (distribution.packaging) { - case TAR: - case ZIP: - Archives.assertElasticsearchStarted(installation); - break; - case DEB: - case RPM: - Packages.assertElasticsearchStarted(sh, installation); - break; - case DOCKER: - case DOCKER_UBI: - case DOCKER_IRON_BANK: - case DOCKER_CLOUD: - case DOCKER_CLOUD_ESS: - Docker.waitForElasticsearchToStart(); - break; - default: - throw new IllegalStateException("Unknown Elasticsearch packaging type."); + case TAR, ZIP -> Archives.assertElasticsearchStarted(installation); + case DEB, RPM -> Packages.assertElasticsearchStarted(sh, installation); + case DOCKER, DOCKER_UBI, DOCKER_IRON_BANK, DOCKER_CLOUD, DOCKER_CLOUD_ESS -> Docker.waitForElasticsearchToStart(); + default -> throw new IllegalStateException("Unknown Elasticsearch packaging type."); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/Distribution.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/Distribution.java index f3fd1becab900..6600514c67f9e 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/Distribution.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/Distribution.java @@ -59,15 +59,10 @@ public boolean isPackage() { * @return whether this distribution is packaged as a Docker image. */ public boolean isDocker() { - switch (packaging) { - case DOCKER: - case DOCKER_UBI: - case DOCKER_IRON_BANK: - case DOCKER_CLOUD: - case DOCKER_CLOUD_ESS: - return true; - } - return false; + return switch (packaging) { + case DOCKER, DOCKER_UBI, DOCKER_IRON_BANK, DOCKER_CLOUD, DOCKER_CLOUD_ESS -> true; + default -> false; + }; } public enum Packaging { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerRun.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerRun.java index 5b1e821399dad..caae6e2635c0f 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerRun.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerRun.java @@ -153,32 +153,14 @@ String build() { * @return an image name */ public static String getImageName(Distribution distribution) { - String suffix; - - switch (distribution.packaging) { - case DOCKER: - suffix = ""; - break; - - case DOCKER_UBI: - suffix = "-ubi8"; - break; - - case DOCKER_IRON_BANK: - suffix = "-ironbank"; - break; - - case DOCKER_CLOUD: - suffix = "-cloud"; - break; - - case DOCKER_CLOUD_ESS: - suffix = "-cloud-ess"; - break; - - default: - throw new IllegalStateException("Unexpected distribution packaging type: " + distribution.packaging); - } + String suffix = switch (distribution.packaging) { + case DOCKER -> ""; + case DOCKER_UBI -> "-ubi8"; + case DOCKER_IRON_BANK -> "-ironbank"; + case DOCKER_CLOUD -> "-cloud"; + case DOCKER_CLOUD_ESS -> "-cloud-ess"; + default -> throw new IllegalStateException("Unexpected distribution packaging type: " + distribution.packaging); + }; return "elasticsearch" + suffix + ":test"; } diff --git a/qa/repository-multi-version/src/test/java/org/elasticsearch/upgrades/MultiVersionRepositoryAccessIT.java b/qa/repository-multi-version/src/test/java/org/elasticsearch/upgrades/MultiVersionRepositoryAccessIT.java index 9c436cf9c5608..1816936e05477 100644 --- a/qa/repository-multi-version/src/test/java/org/elasticsearch/upgrades/MultiVersionRepositoryAccessIT.java +++ b/qa/repository-multi-version/src/test/java/org/elasticsearch/upgrades/MultiVersionRepositoryAccessIT.java @@ -75,18 +75,13 @@ public String toString() { } public static TestStep parse(String value) { - switch (value) { - case "step1": - return STEP1_OLD_CLUSTER; - case "step2": - return STEP2_NEW_CLUSTER; - case "step3": - return STEP3_OLD_CLUSTER; - case "step4": - return STEP4_NEW_CLUSTER; - default: - throw new AssertionError("unknown test step: " + value); - } + return switch (value) { + case "step1" -> STEP1_OLD_CLUSTER; + case "step2" -> STEP2_NEW_CLUSTER; + case "step3" -> STEP3_OLD_CLUSTER; + case "step4" -> STEP4_NEW_CLUSTER; + default -> throw new AssertionError("unknown test step: " + value); + }; } } @@ -126,20 +121,18 @@ public void testCreateAndRestoreSnapshot() throws IOException { final List> snapshots = listSnapshots(repoName); assertThat(snapshots, hasSize(TEST_STEP.ordinal() + 1)); switch (TEST_STEP) { - case STEP2_NEW_CLUSTER: - case STEP4_NEW_CLUSTER: - assertSnapshotStatusSuccessful( - client, - repoName, - snapshots.stream().map(sn -> (String) sn.get("snapshot")).toArray(String[]::new) - ); - break; - case STEP1_OLD_CLUSTER: - assertSnapshotStatusSuccessful(client, repoName, "snapshot-" + TEST_STEP); - break; - case STEP3_OLD_CLUSTER: - assertSnapshotStatusSuccessful(client, repoName, "snapshot-" + TEST_STEP, "snapshot-" + TestStep.STEP3_OLD_CLUSTER); - break; + case STEP2_NEW_CLUSTER, STEP4_NEW_CLUSTER -> assertSnapshotStatusSuccessful( + client, + repoName, + snapshots.stream().map(sn -> (String) sn.get("snapshot")).toArray(String[]::new) + ); + case STEP1_OLD_CLUSTER -> assertSnapshotStatusSuccessful(client, repoName, "snapshot-" + TEST_STEP); + case STEP3_OLD_CLUSTER -> assertSnapshotStatusSuccessful( + client, + repoName, + "snapshot-" + TEST_STEP, + "snapshot-" + TestStep.STEP3_OLD_CLUSTER + ); } if (TEST_STEP == TestStep.STEP3_OLD_CLUSTER) { ensureSnapshotRestoreWorks(client, repoName, "snapshot-" + TestStep.STEP1_OLD_CLUSTER, shards, index); @@ -167,14 +160,8 @@ public void testReadOnlyRepo() throws IOException { } final List> snapshots = listSnapshots(repoName); switch (TEST_STEP) { - case STEP1_OLD_CLUSTER: - assertThat(snapshots, hasSize(1)); - break; - case STEP2_NEW_CLUSTER: - case STEP4_NEW_CLUSTER: - case STEP3_OLD_CLUSTER: - assertThat(snapshots, hasSize(2)); - break; + case STEP1_OLD_CLUSTER -> assertThat(snapshots, hasSize(1)); + case STEP2_NEW_CLUSTER, STEP4_NEW_CLUSTER, STEP3_OLD_CLUSTER -> assertThat(snapshots, hasSize(2)); } if (TEST_STEP == TestStep.STEP1_OLD_CLUSTER || TEST_STEP == TestStep.STEP3_OLD_CLUSTER) { assertSnapshotStatusSuccessful(client, repoName, "snapshot-" + TestStep.STEP1_OLD_CLUSTER); diff --git a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/AbstractRollingTestCase.java b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/AbstractRollingTestCase.java index c905ebf65a01a..768274e817c13 100644 --- a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/AbstractRollingTestCase.java +++ b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/AbstractRollingTestCase.java @@ -18,16 +18,12 @@ protected enum ClusterType { UPGRADED; public static ClusterType parse(String value) { - switch (value) { - case "old_cluster": - return OLD; - case "mixed_cluster": - return MIXED; - case "upgraded_cluster": - return UPGRADED; - default: - throw new AssertionError("unknown cluster type: " + value); - } + return switch (value) { + case "old_cluster" -> OLD; + case "mixed_cluster" -> MIXED; + case "upgraded_cluster" -> UPGRADED; + default -> throw new AssertionError("unknown cluster type: " + value); + }; } } diff --git a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/IndexingIT.java b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/IndexingIT.java index a18270c3fbb1b..0ba74d811293c 100644 --- a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/IndexingIT.java +++ b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/IndexingIT.java @@ -144,18 +144,16 @@ public void testAutoIdWithOpTypeCreate() throws IOException { bulk.setJsonEntity(b); switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { Request createTestIndex = new Request("PUT", "/" + indexName); createTestIndex.setJsonEntity("{\"settings\": {\"index.number_of_replicas\": 0}}"); client().performRequest(createTestIndex); - break; - case MIXED: + } + case MIXED -> { Request waitForGreen = new Request("GET", "/_cluster/health"); waitForGreen.addParameter("wait_for_nodes", "3"); client().performRequest(waitForGreen); - Version minNodeVersion = minNodeVersion(); - if (minNodeVersion.before(Version.V_7_5_0)) { ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(bulk)); assertEquals(400, e.getResponse().getStatusLine().getStatusCode()); @@ -169,19 +167,16 @@ public void testAutoIdWithOpTypeCreate() throws IOException { } else { client().performRequest(bulk); } - break; - case UPGRADED: - client().performRequest(bulk); - break; - default: - throw new UnsupportedOperationException("Unknown cluster type [" + CLUSTER_TYPE + "]"); + } + case UPGRADED -> client().performRequest(bulk); + default -> throw new UnsupportedOperationException("Unknown cluster type [" + CLUSTER_TYPE + "]"); } } public void testDateNanosFormatUpgrade() throws IOException { final String indexName = "test_date_nanos"; switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { Request createIndex = new Request("PUT", "/" + indexName); XContentBuilder mappings = XContentBuilder.builder(XContentType.JSON.xContent()) .startObject() @@ -198,7 +193,6 @@ public void testDateNanosFormatUpgrade() throws IOException { .endObject(); createIndex.setJsonEntity(Strings.toString(mappings)); client().performRequest(createIndex); - Request index = new Request("POST", "/" + indexName + "/_doc/"); XContentBuilder doc = XContentBuilder.builder(XContentType.JSON.xContent()) .startObject() @@ -208,9 +202,8 @@ public void testDateNanosFormatUpgrade() throws IOException { index.addParameter("refresh", "true"); index.setJsonEntity(Strings.toString(doc)); client().performRequest(index); - break; - - case UPGRADED: + } + case UPGRADED -> { Request search = new Request("POST", "/" + indexName + "/_search"); XContentBuilder query = XContentBuilder.builder(XContentType.JSON.xContent()) .startObject() @@ -218,19 +211,14 @@ public void testDateNanosFormatUpgrade() throws IOException { .endObject(); search.setJsonEntity(Strings.toString(query)); Map response = entityAsMap(client().performRequest(search)); - Map bestHit = (Map) ((List) (XContentMapValues.extractValue("hits.hits", response))).get(0); List date = (List) XContentMapValues.extractValue("fields.date", bestHit); assertThat(date.size(), equalTo(1)); assertThat(date.get(0), equalTo("2015-01-01T12:10:30.123Z")); - List dateNanos = (List) XContentMapValues.extractValue("fields.date_nanos", bestHit); assertThat(dateNanos.size(), equalTo(1)); assertThat(dateNanos.get(0), equalTo("2015-01-01T12:10:30.123456789Z")); - break; - - default: - break; + } } } @@ -263,14 +251,15 @@ public void testTsdb() throws IOException { StringBuilder bulk = new StringBuilder(); switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { createTsdbIndex(); tsdbBulk(bulk, TSDB_DIMS.get(0), TSDB_TIMES[0], TSDB_TIMES[1], 0.1); tsdbBulk(bulk, TSDB_DIMS.get(1), TSDB_TIMES[0], TSDB_TIMES[1], -0.1); bulk("tsdb", bulk.toString()); assertTsdbAgg(closeTo(215.95, 0.005), closeTo(-215.95, 0.005)); return; - case MIXED: + } + case MIXED -> { if (FIRST_MIXED_ROUND) { tsdbBulk(bulk, TSDB_DIMS.get(0), TSDB_TIMES[1], TSDB_TIMES[2], 0.1); tsdbBulk(bulk, TSDB_DIMS.get(1), TSDB_TIMES[1], TSDB_TIMES[2], -0.1); @@ -286,7 +275,8 @@ public void testTsdb() throws IOException { bulk("tsdb", bulk.toString()); assertTsdbAgg(closeTo(218.95, 0.005), closeTo(-218.95, 0.005), closeTo(2408.45, 0.005), closeTo(21895, 0.5)); return; - case UPGRADED: + } + case UPGRADED -> { tsdbBulk(bulk, TSDB_DIMS.get(0), TSDB_TIMES[3], TSDB_TIMES[4], 0.1); tsdbBulk(bulk, TSDB_DIMS.get(1), TSDB_TIMES[3], TSDB_TIMES[4], -0.1); tsdbBulk(bulk, TSDB_DIMS.get(2), TSDB_TIMES[3], TSDB_TIMES[4], 1.1); @@ -301,6 +291,7 @@ public void testTsdb() throws IOException { closeTo(-11022.5, 0.5) ); return; + } } } diff --git a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/RecoveryIT.java b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/RecoveryIT.java index f3e9df923433f..88b1bcdabdbe6 100644 --- a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/RecoveryIT.java +++ b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/RecoveryIT.java @@ -125,7 +125,7 @@ public void testRecoveryWithConcurrentIndexing() throws Exception { List nodes = new ArrayList<>(nodeMap.keySet()); switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { Settings.Builder settings = Settings.builder() .put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1) .put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 2) @@ -140,8 +140,8 @@ public void testRecoveryWithConcurrentIndexing() throws Exception { ensureGreen(index); // make sure that we can index while the replicas are recovering updateIndexSettings(index, Settings.builder().put(INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), "primaries")); - break; - case MIXED: + } + case MIXED -> { updateIndexSettings(index, Settings.builder().put(INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), (String) null)); asyncIndexDocs(index, 10, 50).get(); ensureGreen(index); @@ -151,8 +151,8 @@ public void testRecoveryWithConcurrentIndexing() throws Exception { assertCount(index, "_only_nodes:" + nodes.get(2), 60); // make sure that we can index while the replicas are recovering updateIndexSettings(index, Settings.builder().put(INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), "primaries")); - break; - case UPGRADED: + } + case UPGRADED -> { updateIndexSettings(index, Settings.builder().put(INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), (String) null)); asyncIndexDocs(index, 60, 45).get(); ensureGreen(index); @@ -160,9 +160,8 @@ public void testRecoveryWithConcurrentIndexing() throws Exception { assertCount(index, "_only_nodes:" + nodes.get(0), 105); assertCount(index, "_only_nodes:" + nodes.get(1), 105); assertCount(index, "_only_nodes:" + nodes.get(2), 105); - break; - default: - throw new IllegalStateException("unknown type " + CLUSTER_TYPE); + } + default -> throw new IllegalStateException("unknown type " + CLUSTER_TYPE); } } @@ -215,7 +214,7 @@ private String getNodeId(Predicate versionPredicate) throws IOException public void testRelocationWithConcurrentIndexing() throws Exception { final String index = "relocation_with_concurrent_indexing"; switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { Settings.Builder settings = Settings.builder() .put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1) .put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 2) @@ -232,8 +231,8 @@ public void testRelocationWithConcurrentIndexing() throws Exception { // make sure that no shards are allocated, so we can make sure the primary stays on the old node (when one // node stops, we lose the master too, so a replica will not be promoted) updateIndexSettings(index, Settings.builder().put(INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), "none")); - break; - case MIXED: + } + case MIXED -> { final String newNode = getNodeId(v -> v.equals(Version.CURRENT)); final String oldNode = getNodeId(v -> v.before(Version.CURRENT)); // remove the replica and guaranteed the primary is placed on the old node @@ -262,8 +261,8 @@ public void testRelocationWithConcurrentIndexing() throws Exception { ensureGreen(index); client().performRequest(new Request("POST", index + "/_refresh")); assertCount(index, "_only_nodes:" + newNode, 60); - break; - case UPGRADED: + } + case UPGRADED -> { updateIndexSettings( index, Settings.builder() @@ -278,13 +277,11 @@ public void testRelocationWithConcurrentIndexing() throws Exception { ObjectPath objectPath = ObjectPath.createFromResponse(response); final Map nodeMap = objectPath.evaluate("nodes"); List nodes = new ArrayList<>(nodeMap.keySet()); - assertCount(index, "_only_nodes:" + nodes.get(0), 105); assertCount(index, "_only_nodes:" + nodes.get(1), 105); assertCount(index, "_only_nodes:" + nodes.get(2), 105); - break; - default: - throw new IllegalStateException("unknown type " + CLUSTER_TYPE); + } + default -> throw new IllegalStateException("unknown type " + CLUSTER_TYPE); } if (randomBoolean()) { flush(index, randomBoolean()); @@ -355,7 +352,7 @@ public void testRetentionLeasesEstablishedWhenPromotingPrimary() throws Exceptio public void testRetentionLeasesEstablishedWhenRelocatingPrimary() throws Exception { final String index = "recover_and_create_leases_in_relocation"; switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { Settings.Builder settings = Settings.builder() .put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), between(1, 5)) .put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), between(0, 1)) @@ -371,9 +368,8 @@ public void testRetentionLeasesEstablishedWhenRelocatingPrimary() throws Excepti client().performRequest(new Request("POST", "/" + index + "/_flush")); } ensureGreen(index); - break; - - case MIXED: + } + case MIXED -> { // trigger a primary relocation by excluding the last old node with a shard filter final Map nodesMap = ObjectPath.createFromResponse(client().performRequest(new Request("GET", "/_nodes"))) .evaluate("nodes"); @@ -385,7 +381,6 @@ public void testRetentionLeasesEstablishedWhenRelocatingPrimary() throws Excepti oldNodeNames.add((String) nodeDetailsMap.get("name")); } } - if (oldNodeNames.size() == 1) { final String oldNodeName = oldNodeNames.get(0); logger.info("--> excluding index [{}] from node [{}]", index, oldNodeName); @@ -395,12 +390,11 @@ public void testRetentionLeasesEstablishedWhenRelocatingPrimary() throws Excepti } ensureGreen(index); ensurePeerRecoveryRetentionLeasesRenewedAndSynced(index); - break; - - case UPGRADED: + } + case UPGRADED -> { ensureGreen(index); ensurePeerRecoveryRetentionLeasesRenewedAndSynced(index); - break; + } } } diff --git a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/SnapshotBasedRecoveryIT.java b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/SnapshotBasedRecoveryIT.java index c15ca37424add..34efdc5f2207c 100644 --- a/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/SnapshotBasedRecoveryIT.java +++ b/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/SnapshotBasedRecoveryIT.java @@ -44,7 +44,7 @@ public void testSnapshotBasedRecovery() throws Exception { final String repositoryName = "snapshot_based_recovery_repo"; final int numDocs = 200; switch (CLUSTER_TYPE) { - case OLD: + case OLD -> { Settings.Builder settings = Settings.builder() .put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1) .put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0) @@ -54,7 +54,6 @@ public void testSnapshotBasedRecovery() throws Exception { ensureGreen(indexName); indexDocs(indexName, numDocs); flush(indexName, true); - registerRepository( repositoryName, "fs", @@ -64,14 +63,11 @@ public void testSnapshotBasedRecovery() throws Exception { .put(BlobStoreRepository.USE_FOR_PEER_RECOVERY_SETTING.getKey(), true) .build() ); - createSnapshot(repositoryName, "snap", true); - updateIndexSettings(indexName, Settings.builder().put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1)); ensureGreen(indexName); - break; - case MIXED: - case UPGRADED: + } + case MIXED, UPGRADED -> { if (FIRST_MIXED_ROUND) { String upgradedNodeId = getUpgradedNodeId(); @@ -99,14 +95,12 @@ public void testSnapshotBasedRecovery() throws Exception { // Drop replicas updateIndexSettings(indexName, Settings.builder().put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0)); - updateIndexSettings(indexName, Settings.builder().put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1)); ensureGreen(indexName); assertMatchAllReturnsAllDocuments(indexName, numDocs); assertMatchQueryReturnsAllDocuments(indexName, numDocs); - break; - default: - throw new IllegalStateException("unknown type " + CLUSTER_TYPE); + } + default -> throw new IllegalStateException("unknown type " + CLUSTER_TYPE); } } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/HotThreadsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/HotThreadsIT.java index 8191732579392..f539db0c303bd 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/HotThreadsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/HotThreadsIT.java @@ -55,20 +55,12 @@ public void testHotThreadsDontFail() throws ExecutionException, InterruptedExcep } nodesHotThreadsRequestBuilder.setIgnoreIdleThreads(randomBoolean()); if (randomBoolean()) { - switch (randomIntBetween(0, 3)) { - case 3: - type = "mem"; - break; - case 2: - type = "cpu"; - break; - case 1: - type = "wait"; - break; - default: - type = "block"; - break; - } + type = switch (randomIntBetween(0, 3)) { + case 3 -> "mem"; + case 2 -> "cpu"; + case 1 -> "wait"; + default -> "block"; + }; assertThat(type, notNullValue()); nodesHotThreadsRequestBuilder.setType(HotThreads.ReportType.of(type)); } else { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java index e0d2808bd07e2..f598e02f49dc1 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java @@ -370,24 +370,23 @@ public void testSearchTaskDescriptions() { assertEquals(mainTask.get(0).getTaskId(), taskInfo.getParentTaskId()); assertTaskHeaders(taskInfo); switch (taskInfo.getAction()) { - case SearchTransportService.QUERY_ACTION_NAME: - case SearchTransportService.DFS_ACTION_NAME: - assertTrue(taskInfo.getDescription(), Regex.simpleMatch("shardId[[test][*]]", taskInfo.getDescription())); - break; - case SearchTransportService.QUERY_ID_ACTION_NAME: - assertTrue(taskInfo.getDescription(), Regex.simpleMatch("id[*], indices[test]", taskInfo.getDescription())); - break; - case SearchTransportService.FETCH_ID_ACTION_NAME: - assertTrue( - taskInfo.getDescription(), - Regex.simpleMatch("id[*], size[1], lastEmittedDoc[null]", taskInfo.getDescription()) - ); - break; - case SearchTransportService.QUERY_CAN_MATCH_NAME: - assertTrue(taskInfo.getDescription(), Regex.simpleMatch("shardId[[test][*]]", taskInfo.getDescription())); - break; - default: - fail("Unexpected action [" + taskInfo.getAction() + "] with description [" + taskInfo.getDescription() + "]"); + case SearchTransportService.QUERY_ACTION_NAME, SearchTransportService.DFS_ACTION_NAME -> assertTrue( + taskInfo.getDescription(), + Regex.simpleMatch("shardId[[test][*]]", taskInfo.getDescription()) + ); + case SearchTransportService.QUERY_ID_ACTION_NAME -> assertTrue( + taskInfo.getDescription(), + Regex.simpleMatch("id[*], indices[test]", taskInfo.getDescription()) + ); + case SearchTransportService.FETCH_ID_ACTION_NAME -> assertTrue( + taskInfo.getDescription(), + Regex.simpleMatch("id[*], size[1], lastEmittedDoc[null]", taskInfo.getDescription()) + ); + case SearchTransportService.QUERY_CAN_MATCH_NAME -> assertTrue( + taskInfo.getDescription(), + Regex.simpleMatch("shardId[[test][*]]", taskInfo.getDescription()) + ); + default -> fail("Unexpected action [" + taskInfo.getAction() + "] with description [" + taskInfo.getDescription() + "]"); } // assert that all task descriptions have non-zero length assertThat(taskInfo.getDescription().length(), greaterThan(0)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java index 29bb176646e26..f2c4d1b2fa5c9 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java @@ -260,32 +260,26 @@ public void testRandomSingleTermVectors() throws IOException { boolean storeOffsets = false; boolean storeTermVectors = false; switch (config) { - case 0: { + case 0 -> { // do nothing - break; } - case 1: { + case 1 -> { storeTermVectors = true; - break; } - case 2: { + case 2 -> { storeTermVectors = true; storePositions = true; - break; } - case 3: { + case 3 -> { storeTermVectors = true; storeOffsets = true; - break; } - case 4: { + case 4 -> { storeTermVectors = true; storePositions = true; storeOffsets = true; - break; } - default: - throw new IllegalArgumentException("Unsupported option: " + config); + default -> throw new IllegalArgumentException("Unsupported option: " + config); } ft.setStoreTermVectors(storeTermVectors); ft.setStoreTermVectorOffsets(storeOffsets); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterStateDiffIT.java b/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterStateDiffIT.java index 6254bd71a443a..6603a6ee5aee6 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterStateDiffIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterStateDiffIT.java @@ -89,28 +89,15 @@ public void testClusterStateDiffSerialization() throws Exception { if (i > 0) { clusterState = builder.build(); } - switch (randomInt(5)) { - case 0: - builder = randomNodes(clusterState); - break; - case 1: - builder = randomRoutingTable(clusterState); - break; - case 2: - builder = randomBlocks(clusterState); - break; - case 3: - builder = randomClusterStateCustoms(clusterState); - break; - case 4: - builder = randomMetadataChanges(clusterState); - break; - case 5: - builder = randomCoordinationMetadata(clusterState); - break; - default: - throw new IllegalArgumentException("Shouldn't be here"); - } + builder = switch (randomInt(5)) { + case 0 -> randomNodes(clusterState); + case 1 -> randomRoutingTable(clusterState); + case 2 -> randomBlocks(clusterState); + case 3 -> randomClusterStateCustoms(clusterState); + case 4 -> randomMetadataChanges(clusterState); + case 5 -> randomCoordinationMetadata(clusterState); + default -> throw new IllegalArgumentException("Shouldn't be here"); + }; } clusterState = builder.incrementVersion().build(); @@ -366,14 +353,11 @@ private ClusterState.Builder randomBlocks(ClusterState clusterState) { * Returns a random global block */ private ClusterBlock randomGlobalBlock() { - switch (randomInt(2)) { - case 0: - return NoMasterBlockService.NO_MASTER_BLOCK_ALL; - case 1: - return NoMasterBlockService.NO_MASTER_BLOCK_WRITES; - default: - return GatewayService.STATE_NOT_RECOVERED_BLOCK; - } + return switch (randomInt(2)) { + case 0 -> NoMasterBlockService.NO_MASTER_BLOCK_ALL; + case 1 -> NoMasterBlockService.NO_MASTER_BLOCK_WRITES; + default -> GatewayService.STATE_NOT_RECOVERED_BLOCK; + }; } /** @@ -444,22 +428,13 @@ private ClusterState.Builder randomMetadataChanges(ClusterState clusterState) { Metadata metadata = clusterState.metadata(); int changesCount = randomIntBetween(1, 10); for (int i = 0; i < changesCount; i++) { - switch (randomInt(3)) { - case 0: - metadata = randomMetadataSettings(metadata); - break; - case 1: - metadata = randomIndices(metadata); - break; - case 2: - metadata = randomTemplates(metadata); - break; - case 3: - metadata = randomMetadataCustoms(metadata); - break; - default: - throw new IllegalArgumentException("Shouldn't be here"); - } + metadata = switch (randomInt(3)) { + case 0 -> randomMetadataSettings(metadata); + case 1 -> randomIndices(metadata); + case 2 -> randomTemplates(metadata); + case 3 -> randomMetadataCustoms(metadata); + default -> throw new IllegalArgumentException("Shouldn't be here"); + }; } return ClusterState.builder(clusterState).metadata(Metadata.builder(metadata).version(metadata.version() + 1).build()); } @@ -728,38 +703,35 @@ public ClusterState.Builder remove(ClusterState.Builder builder, String name) { @Override public ClusterState.Custom randomCreate(String name) { - switch (randomIntBetween(0, 1)) { - case 0: - return SnapshotsInProgress.EMPTY.withAddedEntry( - new SnapshotsInProgress.Entry( - new Snapshot(randomName("repo"), new SnapshotId(randomName("snap"), UUIDs.randomBase64UUID())), - randomBoolean(), - randomBoolean(), - SnapshotsInProgressSerializationTests.randomState(ImmutableOpenMap.of()), - Collections.emptyMap(), - Collections.emptyList(), - Collections.emptyList(), - Math.abs(randomLong()), - randomIntBetween(0, 1000), - ImmutableOpenMap.of(), - null, - SnapshotInfoTestUtils.randomUserMetadata(), - randomVersion(random()) - ) - ); - case 1: - return new RestoreInProgress.Builder().add( - new RestoreInProgress.Entry( - UUIDs.randomBase64UUID(), - new Snapshot(randomName("repo"), new SnapshotId(randomName("snap"), UUIDs.randomBase64UUID())), - RestoreInProgress.State.fromValue((byte) randomIntBetween(0, 3)), - emptyList(), - ImmutableOpenMap.of() - ) - ).build(); - default: - throw new IllegalArgumentException("Shouldn't be here"); - } + return switch (randomIntBetween(0, 1)) { + case 0 -> SnapshotsInProgress.EMPTY.withAddedEntry( + new SnapshotsInProgress.Entry( + new Snapshot(randomName("repo"), new SnapshotId(randomName("snap"), UUIDs.randomBase64UUID())), + randomBoolean(), + randomBoolean(), + SnapshotsInProgressSerializationTests.randomState(ImmutableOpenMap.of()), + Collections.emptyMap(), + Collections.emptyList(), + Collections.emptyList(), + Math.abs(randomLong()), + randomIntBetween(0, 1000), + ImmutableOpenMap.of(), + null, + SnapshotInfoTestUtils.randomUserMetadata(), + randomVersion(random()) + ) + ); + case 1 -> new RestoreInProgress.Builder().add( + new RestoreInProgress.Entry( + UUIDs.randomBase64UUID(), + new Snapshot(randomName("repo"), new SnapshotId(randomName("snap"), UUIDs.randomBase64UUID())), + RestoreInProgress.State.fromValue((byte) randomIntBetween(0, 3)), + emptyList(), + ImmutableOpenMap.of() + ) + ).build(); + default -> throw new IllegalArgumentException("Shouldn't be here"); + }; } @Override diff --git a/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceIT.java b/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceIT.java index b2f037b8984f3..76a10652a5047 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceIT.java @@ -168,22 +168,20 @@ public void testTemplateUpdate() throws Exception { for (int i = 0; i < 3; i++) { IndexTemplateMetadata templateMetadata = templates.get(i); switch (templateMetadata.getName()) { - case "test_added_template": + case "test_added_template" -> { assertFalse(addedFound); addedFound = true; - break; - case "test_changed_template": + } + case "test_changed_template" -> { assertFalse(changedFound); changedFound = true; assertThat(templateMetadata.getOrder(), equalTo(10)); - break; - case "test_dummy_template": + } + case "test_dummy_template" -> { assertFalse(dummyFound); dummyFound = true; - break; - default: - fail("unexpected template " + templateMetadata.getName()); - break; + } + default -> fail("unexpected template " + templateMetadata.getName()); } } assertTrue(addedFound); @@ -221,18 +219,16 @@ private void assertTemplates() throws Exception { for (int i = 0; i < 2; i++) { IndexTemplateMetadata templateMetadata = templates.get(i); switch (templateMetadata.getName()) { - case "test_added_template": + case "test_added_template" -> { assertFalse(addedFound); addedFound = true; - break; - case "test_changed_template": + } + case "test_changed_template" -> { assertFalse(changedFound); changedFound = true; assertThat(templateMetadata.getOrder(), equalTo(10)); - break; - default: - fail("unexpected template " + templateMetadata.getName()); - break; + } + default -> fail("unexpected template " + templateMetadata.getName()); } } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java index e71990ca8cda6..55fe9661582f1 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java @@ -31,13 +31,11 @@ public class ClusterSearchShardsIT extends ESIntegTestCase { @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { - switch (nodeOrdinal % 2) { - case 1: - return Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings)).put("node.attr.tag", "B").build(); - case 0: - return Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings)).put("node.attr.tag", "A").build(); - } - return super.nodeSettings(nodeOrdinal, otherSettings); + return switch (nodeOrdinal % 2) { + case 1 -> Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings)).put("node.attr.tag", "B").build(); + case 0 -> Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings)).put("node.attr.tag", "A").build(); + default -> super.nodeSettings(nodeOrdinal, otherSettings); + }; } public void testSingleShardAllocation() throws Exception { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/indices/state/CloseWhileRelocatingShardsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/indices/state/CloseWhileRelocatingShardsIT.java index b88091cd85707..601daff94e3de 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/indices/state/CloseWhileRelocatingShardsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/indices/state/CloseWhileRelocatingShardsIT.java @@ -85,11 +85,11 @@ public void testCloseWhileRelocatingShards() throws Exception { final String indexName = "index-" + i; int nbDocs = 0; switch (i) { - case 0: + case 0 -> { logger.debug("creating empty index {}", indexName); createIndex(indexName); - break; - case 1: + } + case 1 -> { nbDocs = scaledRandomIntBetween(1, 100); logger.debug("creating index {} with {} documents", indexName, nbDocs); createIndex(indexName); @@ -99,13 +99,14 @@ public void testCloseWhileRelocatingShards() throws Exception { .mapToObj(n -> client().prepareIndex(indexName).setSource("num", n)) .collect(Collectors.toList()) ); - break; - default: + } + default -> { logger.debug("creating index {} with background indexing", indexName); final BackgroundIndexer indexer = new BackgroundIndexer(indexName, client(), -1, 1); indexers.put(indexName, indexer); indexer.setFailureAssertion(t -> assertException(t, indexName)); waitForDocs(1, indexer); + } } docsPerIndex.put(indexName, (long) nbDocs); indices[i] = indexName; diff --git a/server/src/internalClusterTest/java/org/elasticsearch/indices/stats/IndexStatsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/indices/stats/IndexStatsIT.java index d753527f2aec6..bd7e57996cc49 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/indices/stats/IndexStatsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/indices/stats/IndexStatsIT.java @@ -1098,64 +1098,27 @@ public void testGroupsParam() throws Exception { private static void set(Flag flag, IndicesStatsRequestBuilder builder, boolean set) { switch (flag) { - case Docs: - builder.setDocs(set); - break; - case FieldData: - builder.setFieldData(set); - break; - case QueryCache: - builder.setQueryCache(set); - break; - case Flush: - builder.setFlush(set); - break; - case Get: - builder.setGet(set); - break; - case Indexing: - builder.setIndexing(set); - break; - case Merge: - builder.setMerge(set); - break; - case Refresh: - builder.setRefresh(set); - break; - case Search: - builder.setSearch(set); - break; - case Store: - builder.setStore(set); - break; - case Warmer: - builder.setWarmer(set); - break; - case Completion: - builder.setCompletion(set); - break; - case Segments: - builder.setSegments(set); - break; - case Translog: - builder.setTranslog(set); - break; - case RequestCache: - builder.setRequestCache(set); - break; - case Recovery: - builder.setRecovery(set); - break; - case Bulk: - builder.setBulk(set); - break; - case Shards: + case Docs -> builder.setDocs(set); + case FieldData -> builder.setFieldData(set); + case QueryCache -> builder.setQueryCache(set); + case Flush -> builder.setFlush(set); + case Get -> builder.setGet(set); + case Indexing -> builder.setIndexing(set); + case Merge -> builder.setMerge(set); + case Refresh -> builder.setRefresh(set); + case Search -> builder.setSearch(set); + case Store -> builder.setStore(set); + case Warmer -> builder.setWarmer(set); + case Completion -> builder.setCompletion(set); + case Segments -> builder.setSegments(set); + case Translog -> builder.setTranslog(set); + case RequestCache -> builder.setRequestCache(set); + case Recovery -> builder.setRecovery(set); + case Bulk -> builder.setBulk(set); + case Shards -> // We don't actually expose shards in IndexStats, but this test fails if it isn't handled builder.request().flags().set(Flag.Shards, set); - break; - default: - fail("new flag? " + flag); - break; + default -> fail("new flag? " + flag); } } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/EquivalenceIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/EquivalenceIT.java index 42fe90cb43cd7..43e092beafd97 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/EquivalenceIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/EquivalenceIT.java @@ -139,19 +139,12 @@ public void testRandomRanges() throws Exception { final int numRanges = randomIntBetween(1, 20); final double[][] ranges = new double[numRanges][]; for (int i = 0; i < ranges.length; ++i) { - switch (randomInt(2)) { - case 0: - ranges[i] = new double[] { Double.NEGATIVE_INFINITY, randomInt(100) }; - break; - case 1: - ranges[i] = new double[] { randomInt(100), Double.POSITIVE_INFINITY }; - break; - case 2: - ranges[i] = new double[] { randomInt(100), randomInt(100) }; - break; - default: - throw new AssertionError(); - } + ranges[i] = switch (randomInt(2)) { + case 0 -> new double[] { Double.NEGATIVE_INFINITY, randomInt(100) }; + case 1 -> new double[] { randomInt(100), Double.POSITIVE_INFINITY }; + case 2 -> new double[] { randomInt(100), randomInt(100) }; + default -> throw new AssertionError(); + }; } RangeAggregationBuilder query = range("range").field("values"); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/BooleanTermsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/BooleanTermsIT.java index bc0cb683780ec..103c03564e5a6 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/BooleanTermsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/BooleanTermsIT.java @@ -43,24 +43,21 @@ public void setupSuiteScopeCluster() throws Exception { } final boolean[] multiValue; switch (randomInt(3)) { - case 0: - multiValue = new boolean[0]; - break; - case 1: + case 0 -> multiValue = new boolean[0]; + case 1 -> { numMultiFalses++; multiValue = new boolean[] { false }; - break; - case 2: + } + case 2 -> { numMultiTrues++; multiValue = new boolean[] { true }; - break; - case 3: + } + case 3 -> { numMultiFalses++; numMultiTrues++; multiValue = new boolean[] { false, true }; - break; - default: - throw new AssertionError(); + } + default -> throw new AssertionError(); } builders[i] = client().prepareIndex("idx") .setSource( diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentileRanksIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentileRanksIT.java index 46b6421086703..3e85caa8e86f3 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentileRanksIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentileRanksIT.java @@ -57,17 +57,11 @@ private static double[] randomPercents(long minValue, long maxValue) { final int length = randomIntBetween(1, 20); final double[] percents = new double[length]; for (int i = 0; i < percents.length; ++i) { - switch (randomInt(20)) { - case 0: - percents[i] = minValue; - break; - case 1: - percents[i] = maxValue; - break; - default: - percents[i] = (randomDouble() * (maxValue - minValue)) + minValue; - break; - } + percents[i] = switch (randomInt(20)) { + case 0 -> minValue; + case 1 -> maxValue; + default -> (randomDouble() * (maxValue - minValue)) + minValue; + }; } Arrays.sort(percents); LogManager.getLogger(HDRPercentileRanksIT.class).info("Using values={}", Arrays.toString(percents)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentilesIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentilesIT.java index 0a5d19b7af884..a486f553d2bf9 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentilesIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/HDRPercentilesIT.java @@ -61,15 +61,9 @@ private static double[] randomPercentiles() { final Set uniquedPercentiles = new HashSet<>(); while (uniquedPercentiles.size() < length) { switch (randomInt(20)) { - case 0: - uniquedPercentiles.add(0.0); - break; - case 1: - uniquedPercentiles.add(100.0); - break; - default: - uniquedPercentiles.add(randomDouble() * 100); - break; + case 0 -> uniquedPercentiles.add(0.0); + case 1 -> uniquedPercentiles.add(100.0); + default -> uniquedPercentiles.add(randomDouble() * 100); } } double[] percentiles = uniquedPercentiles.stream().mapToDouble(Double::doubleValue).sorted().toArray(); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentileRanksIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentileRanksIT.java index 7a8cb1fc0d1e4..ba8ba966a68e1 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentileRanksIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentileRanksIT.java @@ -57,17 +57,11 @@ private static double[] randomPercents(long minValue, long maxValue) { final int length = randomIntBetween(1, 20); final double[] percents = new double[length]; for (int i = 0; i < percents.length; ++i) { - switch (randomInt(20)) { - case 0: - percents[i] = minValue; - break; - case 1: - percents[i] = maxValue; - break; - default: - percents[i] = (randomDouble() * (maxValue - minValue)) + minValue; - break; - } + percents[i] = switch (randomInt(20)) { + case 0 -> minValue; + case 1 -> maxValue; + default -> (randomDouble() * (maxValue - minValue)) + minValue; + }; } Arrays.sort(percents); LogManager.getLogger(TDigestPercentileRanksIT.class).info("Using values={}", Arrays.toString(percents)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentilesIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentilesIT.java index d1d89d7c02740..61f546230f9fd 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentilesIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentilesIT.java @@ -60,15 +60,9 @@ private static double[] randomPercentiles() { final Set uniquedPercentiles = new HashSet<>(); for (int i = 0; i < length; ++i) { switch (randomInt(20)) { - case 0: - uniquedPercentiles.add(0.0); - break; - case 1: - uniquedPercentiles.add(100.0); - break; - default: - uniquedPercentiles.add(randomDouble() * 100); - break; + case 0 -> uniquedPercentiles.add(0.0); + case 1 -> uniquedPercentiles.add(100.0); + default -> uniquedPercentiles.add(randomDouble() * 100); } } double[] percentiles = uniquedPercentiles.stream().mapToDouble(Double::doubleValue).sorted().toArray(); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/pipeline/SerialDiffIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/pipeline/SerialDiffIT.java index 6ba6c0b0a6879..cfd1ab155b971 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/pipeline/SerialDiffIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/pipeline/SerialDiffIT.java @@ -69,16 +69,12 @@ public String toString() { private ValuesSourceAggregationBuilder> randomMetric(String name, String field) { int rand = randomIntBetween(0, 3); - switch (rand) { - case 0: - return min(name).field(field); - case 2: - return max(name).field(field); - case 3: - return avg(name).field(field); - default: - return avg(name).field(field); - } + return switch (rand) { + case 0 -> min(name).field(field); + case 2 -> max(name).field(field); + case 3 -> avg(name).field(field); + default -> avg(name).field(field); + }; } private void assertValidIterators(Iterator expectedBucketIter, Iterator expectedCountsIter, Iterator expectedValuesIter) { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/searchafter/SearchAfterIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/searchafter/SearchAfterIT.java index b1e450ef3e45d..18e65423b9a0f 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/searchafter/SearchAfterIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/searchafter/SearchAfterIT.java @@ -185,27 +185,13 @@ public void testWithSimpleTypes() throws Exception { List values = new ArrayList<>(); for (int type : types) { switch (type) { - case 0: - values.add(randomBoolean()); - break; - case 1: - values.add(randomByte()); - break; - case 2: - values.add(randomShort()); - break; - case 3: - values.add(randomInt()); - break; - case 4: - values.add(randomFloat()); - break; - case 5: - values.add(randomDouble()); - break; - case 6: - values.add(randomAlphaOfLengthBetween(5, 20)); - break; + case 0 -> values.add(randomBoolean()); + case 1 -> values.add(randomByte()); + case 2 -> values.add(randomShort()); + case 3 -> values.add(randomInt()); + case 4 -> values.add(randomFloat()); + case 5 -> values.add(randomDouble()); + case 6 -> values.add(randomAlphaOfLengthBetween(5, 20)); } } values.add(UUIDs.randomBase64UUID()); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/CompletionSuggestSearchIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/CompletionSuggestSearchIT.java index 5d39db3911faf..00f1b9d8be08c 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/CompletionSuggestSearchIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/CompletionSuggestSearchIT.java @@ -1285,15 +1285,11 @@ private void createIndexAndMappingAndSettings(Settings settings, CompletionMappi mapping = mapping.startObject() .field("name", contextMapping.getValue().name()) .field("type", contextMapping.getValue().type().name()); - switch (contextMapping.getValue().type()) { - case CATEGORY: - mapping = mapping.field("path", ((CategoryContextMapping) contextMapping.getValue()).getFieldName()); - break; - case GEO: - mapping = mapping.field("path", ((GeoContextMapping) contextMapping.getValue()).getFieldName()) - .field("precision", ((GeoContextMapping) contextMapping.getValue()).getPrecision()); - break; - } + mapping = switch (contextMapping.getValue().type()) { + case CATEGORY -> mapping.field("path", ((CategoryContextMapping) contextMapping.getValue()).getFieldName()); + case GEO -> mapping.field("path", ((GeoContextMapping) contextMapping.getValue()).getFieldName()) + .field("precision", ((GeoContextMapping) contextMapping.getValue()).getPrecision()); + }; mapping = mapping.endObject(); } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/ContextCompletionSuggestSearchIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/ContextCompletionSuggestSearchIT.java index 1e3e12c3f507d..7944bdb595681 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/ContextCompletionSuggestSearchIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/suggest/ContextCompletionSuggestSearchIT.java @@ -700,20 +700,20 @@ private void createIndexAndMappingAndSettings(Settings settings, CompletionMappi .field("name", contextMapping.getValue().name()) .field("type", contextMapping.getValue().type().name()); switch (contextMapping.getValue().type()) { - case CATEGORY: + case CATEGORY -> { final String fieldName = ((CategoryContextMapping) contextMapping.getValue()).getFieldName(); if (fieldName != null) { mapping.field("path", fieldName); categoryContextFields.add(fieldName); } - break; - case GEO: + } + case GEO -> { final String name = ((GeoContextMapping) contextMapping.getValue()).getFieldName(); mapping.field("precision", ((GeoContextMapping) contextMapping.getValue()).getPrecision()); if (name != null) { mapping.field("path", name); } - break; + } } mapping.endObject(); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/versioning/SimpleVersioningIT.java b/server/src/internalClusterTest/java/org/elasticsearch/versioning/SimpleVersioningIT.java index 9c26282fd4148..bc7b396f0b06a 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/versioning/SimpleVersioningIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/versioning/SimpleVersioningIT.java @@ -435,33 +435,32 @@ private interface IDSource { } private IDSource getRandomIDs() { - IDSource ids; final Random random = random(); - switch (random.nextInt(6)) { - case 0: + return switch (random.nextInt(6)) { + case 0 -> { // random simple logger.info("--> use random simple ids"); - ids = new IDSource() { + yield new IDSource() { @Override public String next() { return TestUtil.randomSimpleString(random, 1, 10); } }; - break; - case 1: + } + case 1 -> { // random realistic unicode logger.info("--> use random realistic unicode ids"); - ids = new IDSource() { + yield new IDSource() { @Override public String next() { return TestUtil.randomRealisticUnicodeString(random, 1, 20); } }; - break; - case 2: + } + case 2 -> { // sequential logger.info("--> use sequential ids"); - ids = new IDSource() { + yield new IDSource() { int upto; @Override @@ -469,11 +468,11 @@ public String next() { return Integer.toString(upto++); } }; - break; - case 3: + } + case 3 -> { // zero-pad sequential logger.info("--> use zero-padded sequential ids"); - ids = new IDSource() { + yield new IDSource() { final String zeroPad = String.format(Locale.ROOT, "%0" + TestUtil.nextInt(random, 4, 20) + "d", 0); int upto; @@ -483,11 +482,11 @@ public String next() { return zeroPad.substring(zeroPad.length() - s.length()) + s; } }; - break; - case 4: + } + case 4 -> { // random long logger.info("--> use random long ids"); - ids = new IDSource() { + yield new IDSource() { final int radix = TestUtil.nextInt(random, Character.MIN_RADIX, Character.MAX_RADIX); @Override @@ -495,11 +494,11 @@ public String next() { return Long.toString(random.nextLong() & 0x3ffffffffffffffL, radix); } }; - break; - case 5: + } + case 5 -> { // zero-pad random long logger.info("--> use zero-padded random long ids"); - ids = new IDSource() { + yield new IDSource() { final int radix = TestUtil.nextInt(random, Character.MIN_RADIX, Character.MAX_RADIX); @Override @@ -507,12 +506,9 @@ public String next() { return Long.toString(random.nextLong() & 0x3ffffffffffffffL, radix); } }; - break; - default: - throw new AssertionError(); - } - - return ids; + } + default -> throw new AssertionError(); + }; } private static class IDAndVersion { diff --git a/server/src/main/java/org/elasticsearch/action/DocWriteRequest.java b/server/src/main/java/org/elasticsearch/action/DocWriteRequest.java index 87611099b2207..2b8d5aab61750 100644 --- a/server/src/main/java/org/elasticsearch/action/DocWriteRequest.java +++ b/server/src/main/java/org/elasticsearch/action/DocWriteRequest.java @@ -176,18 +176,13 @@ public String getLowercase() { } public static OpType fromId(byte id) { - switch (id) { - case 0: - return INDEX; - case 1: - return CREATE; - case 2: - return UPDATE; - case 3: - return DELETE; - default: - throw new IllegalArgumentException("Unknown opType: [" + id + "]"); - } + return switch (id) { + case 0 -> INDEX; + case 1 -> CREATE; + case 2 -> UPDATE; + case 3 -> DELETE; + default -> throw new IllegalArgumentException("Unknown opType: [" + id + "]"); + }; } public static OpType fromString(String sOpType) { diff --git a/server/src/main/java/org/elasticsearch/action/DocWriteResponse.java b/server/src/main/java/org/elasticsearch/action/DocWriteResponse.java index 87ce403e30b92..b74c3930d0745 100644 --- a/server/src/main/java/org/elasticsearch/action/DocWriteResponse.java +++ b/server/src/main/java/org/elasticsearch/action/DocWriteResponse.java @@ -81,20 +81,14 @@ public String getLowercase() { public static Result readFrom(StreamInput in) throws IOException { Byte opcode = in.readByte(); - switch (opcode) { - case 0: - return CREATED; - case 1: - return UPDATED; - case 2: - return DELETED; - case 3: - return NOT_FOUND; - case 4: - return NOOP; - default: - throw new IllegalArgumentException("Unknown result code: " + opcode); - } + return switch (opcode) { + case 0 -> CREATED; + case 1 -> UPDATED; + case 2 -> DELETED; + case 3 -> NOT_FOUND; + case 4 -> NOOP; + default -> throw new IllegalArgumentException("Unknown result code: " + opcode); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/GetSnapshotsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/GetSnapshotsRequest.java index 63094ac8febbb..c951fe3267ce4 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/GetSnapshotsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/GetSnapshotsRequest.java @@ -412,24 +412,16 @@ public String toString() { } public static SortBy of(String value) { - switch (value) { - case "start_time": - return START_TIME; - case "name": - return NAME; - case "duration": - return DURATION; - case "index_count": - return INDICES; - case "shard_count": - return SHARDS; - case "failed_shard_count": - return FAILED_SHARDS; - case "repository": - return REPOSITORY; - default: - throw new IllegalArgumentException("unknown sort order [" + value + "]"); - } + return switch (value) { + case "start_time" -> START_TIME; + case "name" -> NAME; + case "duration" -> DURATION; + case "index_count" -> INDICES; + case "shard_count" -> SHARDS; + case "failed_shard_count" -> FAILED_SHARDS; + case "repository" -> REPOSITORY; + default -> throw new IllegalArgumentException("unknown sort order [" + value + "]"); + }; } } @@ -458,32 +450,15 @@ public static After from(@Nullable SnapshotInfo snapshotInfo, SortBy sortBy) { if (snapshotInfo == null) { return null; } - final String afterValue; - switch (sortBy) { - case START_TIME: - afterValue = String.valueOf(snapshotInfo.startTime()); - break; - case NAME: - afterValue = snapshotInfo.snapshotId().getName(); - break; - case DURATION: - afterValue = String.valueOf(snapshotInfo.endTime() - snapshotInfo.startTime()); - break; - case INDICES: - afterValue = String.valueOf(snapshotInfo.indices().size()); - break; - case SHARDS: - afterValue = String.valueOf(snapshotInfo.totalShards()); - break; - case FAILED_SHARDS: - afterValue = String.valueOf(snapshotInfo.failedShards()); - break; - case REPOSITORY: - afterValue = snapshotInfo.repository(); - break; - default: - throw new AssertionError("unknown sort column [" + sortBy + "]"); - } + final String afterValue = switch (sortBy) { + case START_TIME -> String.valueOf(snapshotInfo.startTime()); + case NAME -> snapshotInfo.snapshotId().getName(); + case DURATION -> String.valueOf(snapshotInfo.endTime() - snapshotInfo.startTime()); + case INDICES -> String.valueOf(snapshotInfo.indices().size()); + case SHARDS -> String.valueOf(snapshotInfo.totalShards()); + case FAILED_SHARDS -> String.valueOf(snapshotInfo.failedShards()); + case REPOSITORY -> snapshotInfo.repository(); + }; return new After(afterValue, snapshotInfo.repository(), snapshotInfo.snapshotId().getName()); } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/TransportGetSnapshotsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/TransportGetSnapshotsAction.java index ea4c0fb60c227..37f2cfee909be 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/TransportGetSnapshotsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/TransportGetSnapshotsAction.java @@ -577,32 +577,15 @@ private static SnapshotsInRepo sortSnapshots( int size, SortOrder order ) { - final Comparator comparator; - switch (sortBy) { - case START_TIME: - comparator = BY_START_TIME; - break; - case NAME: - comparator = BY_NAME; - break; - case DURATION: - comparator = BY_DURATION; - break; - case INDICES: - comparator = BY_INDICES_COUNT; - break; - case SHARDS: - comparator = BY_SHARDS_COUNT; - break; - case FAILED_SHARDS: - comparator = BY_FAILED_SHARDS_COUNT; - break; - case REPOSITORY: - comparator = BY_REPOSITORY; - break; - default: - throw new AssertionError("unexpected sort column [" + sortBy + "]"); - } + final Comparator comparator = switch (sortBy) { + case START_TIME -> BY_START_TIME; + case NAME -> BY_NAME; + case DURATION -> BY_DURATION; + case INDICES -> BY_INDICES_COUNT; + case SHARDS -> BY_SHARDS_COUNT; + case FAILED_SHARDS -> BY_FAILED_SHARDS_COUNT; + case REPOSITORY -> BY_REPOSITORY; + }; Stream infos = snapshotInfos.stream(); @@ -632,31 +615,31 @@ private static Predicate buildAfterPredicate( final String snapshotName = after.snapshotName(); final String repoName = after.repoName(); final String value = after.value(); - switch (sortBy) { - case START_TIME: - return filterByLongOffset(SnapshotInfo::startTime, Long.parseLong(value), snapshotName, repoName, order); - case NAME: + return switch (sortBy) { + case START_TIME -> filterByLongOffset(SnapshotInfo::startTime, Long.parseLong(value), snapshotName, repoName, order); + case NAME -> // TODO: cover via pre-flight predicate - return order == SortOrder.ASC + order == SortOrder.ASC ? (info -> compareName(snapshotName, repoName, info) < 0) : (info -> compareName(snapshotName, repoName, info) > 0); - case DURATION: - return filterByLongOffset(info -> info.endTime() - info.startTime(), Long.parseLong(value), snapshotName, repoName, order); - case INDICES: + case DURATION -> filterByLongOffset( + info -> info.endTime() - info.startTime(), + Long.parseLong(value), + snapshotName, + repoName, + order + ); + case INDICES -> // TODO: cover via pre-flight predicate - return filterByLongOffset(info -> info.indices().size(), Integer.parseInt(value), snapshotName, repoName, order); - case SHARDS: - return filterByLongOffset(SnapshotInfo::totalShards, Integer.parseInt(value), snapshotName, repoName, order); - case FAILED_SHARDS: - return filterByLongOffset(SnapshotInfo::failedShards, Integer.parseInt(value), snapshotName, repoName, order); - case REPOSITORY: + filterByLongOffset(info -> info.indices().size(), Integer.parseInt(value), snapshotName, repoName, order); + case SHARDS -> filterByLongOffset(SnapshotInfo::totalShards, Integer.parseInt(value), snapshotName, repoName, order); + case FAILED_SHARDS -> filterByLongOffset(SnapshotInfo::failedShards, Integer.parseInt(value), snapshotName, repoName, order); + case REPOSITORY -> // TODO: cover via pre-flight predicate - return order == SortOrder.ASC + order == SortOrder.ASC ? (info -> compareRepositoryName(snapshotName, repoName, info) < 0) : (info -> compareRepositoryName(snapshotName, repoName, info) > 0); - default: - throw new AssertionError("unexpected sort column [" + sortBy + "]"); - } + }; } private static Predicate filterByLongOffset( diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStage.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStage.java index 14811638a2cb9..6065b44f4e7ad 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStage.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStage.java @@ -65,19 +65,13 @@ public boolean completed() { * @return state */ public static SnapshotIndexShardStage fromValue(byte value) { - switch (value) { - case 0: - return INIT; - case 1: - return STARTED; - case 2: - return FINALIZE; - case 3: - return DONE; - case 4: - return FAILURE; - default: - throw new IllegalArgumentException("No snapshot shard stage for value [" + value + "]"); - } + return switch (value) { + case 0 -> INIT; + case 1 -> STARTED; + case 2 -> FINALIZE; + case 3 -> DONE; + case 4 -> FAILURE; + default -> throw new IllegalArgumentException("No snapshot shard stage for value [" + value + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStatus.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStatus.java index 14a9ad4c28d9d..c19031c201aaa 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStatus.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotIndexShardStatus.java @@ -60,25 +60,14 @@ public SnapshotIndexShardStatus(StreamInput in) throws IOException { SnapshotIndexShardStatus(ShardId shardId, IndexShardSnapshotStatus.Copy indexShardStatus, String nodeId) { super(shardId); - switch (indexShardStatus.getStage()) { - case INIT: - stage = SnapshotIndexShardStage.INIT; - break; - case STARTED: - stage = SnapshotIndexShardStage.STARTED; - break; - case FINALIZE: - stage = SnapshotIndexShardStage.FINALIZE; - break; - case DONE: - stage = SnapshotIndexShardStage.DONE; - break; - case FAILURE: - stage = SnapshotIndexShardStage.FAILURE; - break; - default: - throw new IllegalArgumentException("Unknown stage type " + indexShardStatus.getStage()); - } + stage = switch (indexShardStatus.getStage()) { + case INIT -> SnapshotIndexShardStage.INIT; + case STARTED -> SnapshotIndexShardStage.STARTED; + case FINALIZE -> SnapshotIndexShardStage.FINALIZE; + case DONE -> SnapshotIndexShardStage.DONE; + case FAILURE -> SnapshotIndexShardStage.FAILURE; + default -> throw new IllegalArgumentException("Unknown stage type " + indexShardStatus.getStage()); + }; this.stats = new SnapshotStats( indexShardStatus.getStartTime(), indexShardStatus.getTotalTime(), diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotShardsStats.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotShardsStats.java index e66bf0af476f1..5bbc5368505db 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotShardsStats.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotShardsStats.java @@ -36,23 +36,12 @@ public class SnapshotShardsStats implements ToXContentObject { for (SnapshotIndexShardStatus shard : shards) { totalShards++; switch (shard.getStage()) { - case INIT: - initializingShards++; - break; - case STARTED: - startedShards++; - break; - case FINALIZE: - finalizingShards++; - break; - case DONE: - doneShards++; - break; - case FAILURE: - failedShards++; - break; - default: - throw new IllegalArgumentException("Unknown stage type " + shard.getStage()); + case INIT -> initializingShards++; + case STARTED -> startedShards++; + case FINALIZE -> finalizingShards++; + case DONE -> doneShards++; + case FAILURE -> failedShards++; + default -> throw new IllegalArgumentException("Unknown stage type " + shard.getStage()); } } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/TransportSnapshotsStatusAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/TransportSnapshotsStatusAction.java index eefe7528de618..326b577a9634f 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/TransportSnapshotsStatusAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/TransportSnapshotsStatusAction.java @@ -220,24 +220,11 @@ private void buildResponse( // This can happen if nodes drop out of the cluster completely or restart during the snapshot. // We rebuild the information they would have provided from their in memory state from the cluster // state and the repository contents in the below logic - final SnapshotIndexShardStage stage; - switch (shardEntry.getValue().state()) { - case FAILED: - case ABORTED: - case MISSING: - stage = SnapshotIndexShardStage.FAILURE; - break; - case INIT: - case WAITING: - case QUEUED: - stage = SnapshotIndexShardStage.STARTED; - break; - case SUCCESS: - stage = SnapshotIndexShardStage.DONE; - break; - default: - throw new IllegalArgumentException("Unknown snapshot state " + shardEntry.getValue().state()); - } + final SnapshotIndexShardStage stage = switch (shardEntry.getValue().state()) { + case FAILED, ABORTED, MISSING -> SnapshotIndexShardStage.FAILURE; + case INIT, WAITING, QUEUED -> SnapshotIndexShardStage.STARTED; + case SUCCESS -> SnapshotIndexShardStage.DONE; + }; final SnapshotIndexShardStatus shardStatus; if (stage == SnapshotIndexShardStage.DONE) { // Shard snapshot completed successfully so we should be able to load the exact statistics for this @@ -342,20 +329,14 @@ private void loadRepositoryData( IndexShardSnapshotStatus.Copy lastSnapshotStatus = shardStatus.getValue().asCopy(); shardStatusBuilder.add(new SnapshotIndexShardStatus(shardStatus.getKey(), lastSnapshotStatus)); } - final SnapshotsInProgress.State state; - switch (snapshotInfo.state()) { - case FAILED: - state = SnapshotsInProgress.State.FAILED; - break; - case SUCCESS: - case PARTIAL: + final SnapshotsInProgress.State state = switch (snapshotInfo.state()) { + case FAILED -> SnapshotsInProgress.State.FAILED; + case SUCCESS, PARTIAL -> // Translating both PARTIAL and SUCCESS to SUCCESS for now // TODO: add the differentiation on the metadata level in the next major release - state = SnapshotsInProgress.State.SUCCESS; - break; - default: - throw new IllegalArgumentException("Unknown snapshot state " + snapshotInfo.state()); - } + SnapshotsInProgress.State.SUCCESS; + default -> throw new IllegalArgumentException("Unexpected snapshot state " + snapshotInfo.state()); + }; final long startTime = snapshotInfo.startTime(); final long endTime = snapshotInfo.endTime(); assert endTime >= startTime || (endTime == 0L && snapshotInfo.state().completed() == false) diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java b/server/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java index 739dbf07f4e55..bc11b7e06ff57 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/alias/IndicesAliasesRequest.java @@ -106,16 +106,12 @@ public byte value() { } public static Type fromValue(byte value) { - switch (value) { - case 0: - return ADD; - case 1: - return REMOVE; - case 2: - return REMOVE_INDEX; - default: - throw new IllegalArgumentException("No type for action [" + value + "]"); - } + return switch (value) { + case 0 -> ADD; + case 1 -> REMOVE; + case 2 -> REMOVE_INDEX; + default -> throw new IllegalArgumentException("No type for action [" + value + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java b/server/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java index b01aa48df6a4c..44478331629cf 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java @@ -131,7 +131,7 @@ protected void masterOperation( }).collect(Collectors.toList()); concreteIndices = nonBackingIndices.toArray(Index[]::new); switch (action.actionType()) { - case ADD: + case ADD -> { // Fail if parameters are used that data stream aliases don't support: if (action.routing() != null) { throw new IllegalArgumentException("aliases that point to data streams don't support routing"); @@ -159,7 +159,8 @@ protected void masterOperation( } } continue; - case REMOVE: + } + case REMOVE -> { for (String dataStreamName : concreteDataStreams) { for (String alias : concreteDataStreamAliases(action, state.metadata(), dataStreamName)) { finalActions.add(new AliasAction.RemoveDataStreamAlias(alias, dataStreamName, action.mustExist())); @@ -168,12 +169,11 @@ protected void masterOperation( if (nonBackingIndices.isEmpty() == false) { // Regular aliases/indices match as well with the provided expression. // (Only when adding new aliases, matching both data streams and indices is disallowed) - break; } else { continue; } - default: - throw new IllegalArgumentException("Unsupported action [" + action.actionType() + "]"); + } + default -> throw new IllegalArgumentException("Unsupported action [" + action.actionType() + "]"); } } else { concreteIndices = indexNameExpressionResolver.concreteIndices(state, request.indicesOptions(), false, action.indices()); diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/IndexDiskUsageAnalyzer.java b/server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/IndexDiskUsageAnalyzer.java index 9f3da489c8f99..db7c59faf768d 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/IndexDiskUsageAnalyzer.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/IndexDiskUsageAnalyzer.java @@ -244,26 +244,20 @@ void analyzeDocValues(SegmentReader reader, IndexDiskUsageStats stats) throws IO cancellationChecker.checkForCancellation(); directory.resetBytesRead(); switch (dvType) { - case NUMERIC: - iterateDocValues(maxDocs, () -> docValuesReader.getNumeric(field), NumericDocValues::longValue); - break; - case SORTED_NUMERIC: - iterateDocValues(maxDocs, () -> docValuesReader.getSortedNumeric(field), dv -> { - for (int i = 0; i < dv.docValueCount(); i++) { - cancellationChecker.logEvent(); - dv.nextValue(); - } - }); - break; - case BINARY: - iterateDocValues(maxDocs, () -> docValuesReader.getBinary(field), BinaryDocValues::binaryValue); - break; - case SORTED: + case NUMERIC -> iterateDocValues(maxDocs, () -> docValuesReader.getNumeric(field), NumericDocValues::longValue); + case SORTED_NUMERIC -> iterateDocValues(maxDocs, () -> docValuesReader.getSortedNumeric(field), dv -> { + for (int i = 0; i < dv.docValueCount(); i++) { + cancellationChecker.logEvent(); + dv.nextValue(); + } + }); + case BINARY -> iterateDocValues(maxDocs, () -> docValuesReader.getBinary(field), BinaryDocValues::binaryValue); + case SORTED -> { SortedDocValues sorted = iterateDocValues(maxDocs, () -> docValuesReader.getSorted(field), SortedDocValues::ordValue); sorted.lookupOrd(0); sorted.lookupOrd(sorted.getValueCount() - 1); - break; - case SORTED_SET: + } + case SORTED_SET -> { SortedSetDocValues sortedSet = iterateDocValues(maxDocs, () -> docValuesReader.getSortedSet(field), dv -> { while (dv.nextOrd() != SortedSetDocValues.NO_MORE_ORDS) { cancellationChecker.logEvent(); @@ -271,10 +265,11 @@ void analyzeDocValues(SegmentReader reader, IndexDiskUsageStats stats) throws IO }); sortedSet.lookupOrd(0); sortedSet.lookupOrd(sortedSet.getValueCount() - 1); - break; - default: + } + default -> { assert false : "Unknown docValues type [" + dvType + "]"; throw new IllegalStateException("Unknown docValues type [" + dvType + "]"); + } } stats.addDocValues(field.name, directory.getBytesRead()); } diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/resolve/ResolveIndexAction.java b/server/src/main/java/org/elasticsearch/action/admin/indices/resolve/ResolveIndexAction.java index 7ca7001bd547b..52db06928ec7f 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/resolve/ResolveIndexAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/resolve/ResolveIndexAction.java @@ -569,10 +569,9 @@ private static void enrichIndexAbstraction( IndexAbstraction ia = lookup.get(indexAbstraction); if (ia != null) { switch (ia.getType()) { - case CONCRETE_INDEX: + case CONCRETE_INDEX -> { IndexMetadata writeIndex = metadata.index(ia.getWriteIndex()); String[] aliasNames = writeIndex.getAliases().keySet().stream().sorted().toArray(String[]::new); - List attributes = new ArrayList<>(); attributes.add(writeIndex.getState() == IndexMetadata.State.OPEN ? "open" : "closed"); if (ia.isHidden()) { @@ -583,7 +582,6 @@ private static void enrichIndexAbstraction( attributes.add("frozen"); } attributes.sort(String::compareTo); - indices.add( new ResolvedIndex( ia.getName(), @@ -592,13 +590,13 @@ private static void enrichIndexAbstraction( ia.getParentDataStream() == null ? null : ia.getParentDataStream().getName() ) ); - break; - case ALIAS: + } + case ALIAS -> { String[] indexNames = ia.getIndices().stream().map(Index::getName).toArray(String[]::new); Arrays.sort(indexNames); aliases.add(new ResolvedAlias(ia.getName(), indexNames)); - break; - case DATA_STREAM: + } + case DATA_STREAM -> { IndexAbstraction.DataStream dataStream = (IndexAbstraction.DataStream) ia; String[] backingIndices = dataStream.getIndices().stream().map(Index::getName).toArray(String[]::new); dataStreams.add( @@ -608,9 +606,8 @@ private static void enrichIndexAbstraction( dataStream.getDataStream().getTimeStampField().getName() ) ); - break; - default: - throw new IllegalStateException("unknown index abstraction type: " + ia.getType()); + } + default -> throw new IllegalStateException("unknown index abstraction type: " + ia.getType()); } } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java b/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java index e7b148c9a179d..ab0779738352e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java @@ -112,32 +112,30 @@ public RolloverResult rolloverClusterState( ) throws Exception { validate(currentState.metadata(), rolloverTarget, newIndexName, createIndexRequest); final IndexAbstraction indexAbstraction = currentState.metadata().getIndicesLookup().get(rolloverTarget); - switch (indexAbstraction.getType()) { - case ALIAS: - return rolloverAlias( - currentState, - (IndexAbstraction.Alias) indexAbstraction, - rolloverTarget, - newIndexName, - createIndexRequest, - metConditions, - silent, - onlyValidate - ); - case DATA_STREAM: - return rolloverDataStream( - currentState, - (IndexAbstraction.DataStream) indexAbstraction, - rolloverTarget, - createIndexRequest, - metConditions, - silent, - onlyValidate - ); - default: + return switch (indexAbstraction.getType()) { + case ALIAS -> rolloverAlias( + currentState, + (IndexAbstraction.Alias) indexAbstraction, + rolloverTarget, + newIndexName, + createIndexRequest, + metConditions, + silent, + onlyValidate + ); + case DATA_STREAM -> rolloverDataStream( + currentState, + (IndexAbstraction.DataStream) indexAbstraction, + rolloverTarget, + createIndexRequest, + metConditions, + silent, + onlyValidate + ); + default -> // the validate method above prevents this case throw new IllegalStateException("unable to roll over type [" + indexAbstraction.getType().getDisplayName() + "]"); - } + }; } public void validateIndexName(ClusterState state, String index) { @@ -155,15 +153,13 @@ public NameResolution resolveRolloverNames( ) { validate(currentState.metadata(), rolloverTarget, newIndexName, createIndexRequest); final IndexAbstraction indexAbstraction = currentState.metadata().getIndicesLookup().get(rolloverTarget); - switch (indexAbstraction.getType()) { - case ALIAS: - return resolveAliasRolloverNames(currentState.metadata(), indexAbstraction, newIndexName); - case DATA_STREAM: - return resolveDataStreamRolloverNames(currentState.getMetadata(), (IndexAbstraction.DataStream) indexAbstraction); - default: + return switch (indexAbstraction.getType()) { + case ALIAS -> resolveAliasRolloverNames(currentState.metadata(), indexAbstraction, newIndexName); + case DATA_STREAM -> resolveDataStreamRolloverNames(currentState.getMetadata(), (IndexAbstraction.DataStream) indexAbstraction); + default -> // the validate method above prevents this case throw new IllegalStateException("unable to roll over type [" + indexAbstraction.getType().getDisplayName() + "]"); - } + }; } public static class NameResolution { diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/settings/get/GetSettingsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/indices/settings/get/GetSettingsResponse.java index c97795f7daefb..f0560e5379548 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/settings/get/GetSettingsResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/settings/get/GetSettingsResponse.java @@ -107,14 +107,9 @@ private static void parseSettingsField( if (parser.currentToken() == XContentParser.Token.START_OBJECT) { switch (parser.currentName()) { - case "settings": - indexToSettings.put(currentIndexName, Settings.fromXContent(parser)); - break; - case "defaults": - indexToDefaultSettings.put(currentIndexName, Settings.fromXContent(parser)); - break; - default: - parser.skipChildren(); + case "settings" -> indexToSettings.put(currentIndexName, Settings.fromXContent(parser)); + case "defaults" -> indexToDefaultSettings.put(currentIndexName, Settings.fromXContent(parser)); + default -> parser.skipChildren(); } } else if (parser.currentToken() == XContentParser.Token.START_ARRAY) { parser.skipChildren(); diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoresResponse.java b/server/src/main/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoresResponse.java index 60dcc78a8447b..efa81c72615ce 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoresResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoresResponse.java @@ -69,29 +69,21 @@ public enum AllocationStatus { } private static AllocationStatus fromId(byte id) { - switch (id) { - case 0: - return PRIMARY; - case 1: - return REPLICA; - case 2: - return UNUSED; - default: - throw new IllegalArgumentException("unknown id for allocation status [" + id + "]"); - } + return switch (id) { + case 0 -> PRIMARY; + case 1 -> REPLICA; + case 2 -> UNUSED; + default -> throw new IllegalArgumentException("unknown id for allocation status [" + id + "]"); + }; } public String value() { - switch (id) { - case 0: - return "primary"; - case 1: - return "replica"; - case 2: - return "unused"; - default: - throw new IllegalArgumentException("unknown id for allocation status [" + id + "]"); - } + return switch (id) { + case 0 -> "primary"; + case 1 -> "replica"; + case 2 -> "unused"; + default -> throw new IllegalArgumentException("unknown id for allocation status [" + id + "]"); + }; } private static AllocationStatus readFrom(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/stats/CommonStats.java b/server/src/main/java/org/elasticsearch/action/admin/indices/stats/CommonStats.java index 999d516cb91d8..e12812bb8c311 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/stats/CommonStats.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/stats/CommonStats.java @@ -109,62 +109,25 @@ public CommonStats(CommonStatsFlags flags) { for (CommonStatsFlags.Flag flag : setFlags) { switch (flag) { - case Docs: - docs = new DocsStats(); - break; - case Store: - store = new StoreStats(); - break; - case Indexing: - indexing = new IndexingStats(); - break; - case Get: - get = new GetStats(); - break; - case Search: - search = new SearchStats(); - break; - case Merge: - merge = new MergeStats(); - break; - case Refresh: - refresh = new RefreshStats(); - break; - case Flush: - flush = new FlushStats(); - break; - case Warmer: - warmer = new WarmerStats(); - break; - case QueryCache: - queryCache = new QueryCacheStats(); - break; - case FieldData: - fieldData = new FieldDataStats(); - break; - case Completion: - completion = new CompletionStats(); - break; - case Segments: - segments = new SegmentsStats(); - break; - case Translog: - translog = new TranslogStats(); - break; - case RequestCache: - requestCache = new RequestCacheStats(); - break; - case Recovery: - recoveryStats = new RecoveryStats(); - break; - case Bulk: - bulk = new BulkStats(); - break; - case Shards: - shards = new ShardCountStats(); - break; - default: - throw new IllegalStateException("Unknown Flag: " + flag); + case Docs -> docs = new DocsStats(); + case Store -> store = new StoreStats(); + case Indexing -> indexing = new IndexingStats(); + case Get -> get = new GetStats(); + case Search -> search = new SearchStats(); + case Merge -> merge = new MergeStats(); + case Refresh -> refresh = new RefreshStats(); + case Flush -> flush = new FlushStats(); + case Warmer -> warmer = new WarmerStats(); + case QueryCache -> queryCache = new QueryCacheStats(); + case FieldData -> fieldData = new FieldDataStats(); + case Completion -> completion = new CompletionStats(); + case Segments -> segments = new SegmentsStats(); + case Translog -> translog = new TranslogStats(); + case RequestCache -> requestCache = new RequestCacheStats(); + case Recovery -> recoveryStats = new RecoveryStats(); + case Bulk -> bulk = new BulkStats(); + case Shards -> shards = new ShardCountStats(); + default -> throw new IllegalStateException("Unknown Flag: " + flag); } } } @@ -174,63 +137,27 @@ public CommonStats(IndicesQueryCache indicesQueryCache, IndexShard indexShard, C for (CommonStatsFlags.Flag flag : setFlags) { try { switch (flag) { - case Docs: - docs = indexShard.docStats(); - break; - case Store: - store = indexShard.storeStats(); - break; - case Indexing: - indexing = indexShard.indexingStats(); - break; - case Get: - get = indexShard.getStats(); - break; - case Search: - search = indexShard.searchStats(flags.groups()); - break; - case Merge: - merge = indexShard.mergeStats(); - break; - case Refresh: - refresh = indexShard.refreshStats(); - break; - case Flush: - flush = indexShard.flushStats(); - break; - case Warmer: - warmer = indexShard.warmerStats(); - break; - case QueryCache: - queryCache = indicesQueryCache.getStats(indexShard.shardId()); - break; - case FieldData: - fieldData = indexShard.fieldDataStats(flags.fieldDataFields()); - break; - case Completion: - completion = indexShard.completionStats(flags.completionDataFields()); - break; - case Segments: - segments = indexShard.segmentStats(flags.includeSegmentFileSizes(), flags.includeUnloadedSegments()); - break; - case Translog: - translog = indexShard.translogStats(); - break; - case RequestCache: - requestCache = indexShard.requestCache().stats(); - break; - case Recovery: - recoveryStats = indexShard.recoveryStats(); - break; - case Bulk: - bulk = indexShard.bulkStats(); - break; - case Shards: + case Docs -> docs = indexShard.docStats(); + case Store -> store = indexShard.storeStats(); + case Indexing -> indexing = indexShard.indexingStats(); + case Get -> get = indexShard.getStats(); + case Search -> search = indexShard.searchStats(flags.groups()); + case Merge -> merge = indexShard.mergeStats(); + case Refresh -> refresh = indexShard.refreshStats(); + case Flush -> flush = indexShard.flushStats(); + case Warmer -> warmer = indexShard.warmerStats(); + case QueryCache -> queryCache = indicesQueryCache.getStats(indexShard.shardId()); + case FieldData -> fieldData = indexShard.fieldDataStats(flags.fieldDataFields()); + case Completion -> completion = indexShard.completionStats(flags.completionDataFields()); + case Segments -> segments = indexShard.segmentStats(flags.includeSegmentFileSizes(), flags.includeUnloadedSegments()); + case Translog -> translog = indexShard.translogStats(); + case RequestCache -> requestCache = indexShard.requestCache().stats(); + case Recovery -> recoveryStats = indexShard.recoveryStats(); + case Bulk -> bulk = indexShard.bulkStats(); + case Shards -> // Setting to 1 because the single IndexShard passed to this method implies 1 shard shards = new ShardCountStats(1); - break; - default: - throw new IllegalStateException("Unknown Flag: " + flag); + default -> throw new IllegalStateException("Unknown Flag: " + flag); } } catch (AlreadyClosedException e) { // shard is closed - no stats is fine diff --git a/server/src/main/java/org/elasticsearch/action/bulk/BulkItemResponse.java b/server/src/main/java/org/elasticsearch/action/bulk/BulkItemResponse.java index 11f3147c93d82..b5a6089b0888a 100644 --- a/server/src/main/java/org/elasticsearch/action/bulk/BulkItemResponse.java +++ b/server/src/main/java/org/elasticsearch/action/bulk/BulkItemResponse.java @@ -523,33 +523,23 @@ private void writeResponseType(StreamOutput out) throws IOException { private static DocWriteResponse readResponse(ShardId shardId, StreamInput in) throws IOException { int type = in.readByte(); - switch (type) { - case 0: - return new IndexResponse(shardId, in); - case 1: - return new DeleteResponse(shardId, in); - case 2: - return null; - case 3: - return new UpdateResponse(shardId, in); - default: - throw new IllegalArgumentException("Unexpected type [" + type + "]"); - } + return switch (type) { + case 0 -> new IndexResponse(shardId, in); + case 1 -> new DeleteResponse(shardId, in); + case 2 -> null; + case 3 -> new UpdateResponse(shardId, in); + default -> throw new IllegalArgumentException("Unexpected type [" + type + "]"); + }; } private static DocWriteResponse readResponse(StreamInput in) throws IOException { int type = in.readByte(); - switch (type) { - case 0: - return new IndexResponse(in); - case 1: - return new DeleteResponse(in); - case 2: - return null; - case 3: - return new UpdateResponse(in); - default: - throw new IllegalArgumentException("Unexpected type [" + type + "]"); - } + return switch (type) { + case 0 -> new IndexResponse(in); + case 1 -> new DeleteResponse(in); + case 2 -> null; + case 3 -> new UpdateResponse(in); + default -> throw new IllegalArgumentException("Unexpected type [" + type + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/action/bulk/BulkPrimaryExecutionContext.java b/server/src/main/java/org/elasticsearch/action/bulk/BulkPrimaryExecutionContext.java index 254650b004139..144880796a3d3 100644 --- a/server/src/main/java/org/elasticsearch/action/bulk/BulkPrimaryExecutionContext.java +++ b/server/src/main/java/org/elasticsearch/action/bulk/BulkPrimaryExecutionContext.java @@ -239,7 +239,7 @@ public void markOperationAsExecuted(Engine.Result result) { final BulkItemRequest current = getCurrentItem(); DocWriteRequest docWriteRequest = getRequestToExecute(); switch (result.getResultType()) { - case SUCCESS: + case SUCCESS -> { final DocWriteResponse response; if (result.getOperationType() == Engine.Operation.TYPE.INDEX) { Engine.IndexResult indexResult = (Engine.IndexResult) result; @@ -269,25 +269,22 @@ public void markOperationAsExecuted(Engine.Result result) { // set a blank ShardInfo so we can safely send it to the replicas. We won't use it in the real response though. executionResult.getResponse().setShardInfo(new ReplicationResponse.ShardInfo()); locationToSync = TransportWriteAction.locationToSync(locationToSync, result.getTranslogLocation()); - break; - case FAILURE: - executionResult = BulkItemResponse.failure( - current.id(), - docWriteRequest.opType(), - // Make sure to use request.index() here, if you - // use docWriteRequest.index() it will use the - // concrete index instead of an alias if used! - new BulkItemResponse.Failure( - request.index(), - docWriteRequest.id(), - result.getFailure(), - result.getSeqNo(), - result.getTerm() - ) - ); - break; - default: - throw new AssertionError("unknown result type for " + getCurrentItem() + ": " + result.getResultType()); + } + case FAILURE -> executionResult = BulkItemResponse.failure( + current.id(), + docWriteRequest.opType(), + // Make sure to use request.index() here, if you + // use docWriteRequest.index() it will use the + // concrete index instead of an alias if used! + new BulkItemResponse.Failure( + request.index(), + docWriteRequest.id(), + result.getFailure(), + result.getSeqNo(), + result.getTerm() + ) + ); + default -> throw new AssertionError("unknown result type for " + getCurrentItem() + ": " + result.getResultType()); } currentItemState = ItemProcessingState.EXECUTED; } diff --git a/server/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java b/server/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java index 0ca795602b6b1..f099c792f6a09 100644 --- a/server/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java +++ b/server/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java @@ -525,10 +525,8 @@ protected void doRun() { IndexRouting indexRouting = concreteIndices.routing(concreteIndex); - int shardId; - switch (docWriteRequest.opType()) { - case CREATE: - case INDEX: + int shardId = switch (docWriteRequest.opType()) { + case CREATE, INDEX -> { prohibitAppendWritesInBackingIndices(docWriteRequest, metadata); prohibitCustomRoutingOnDataStream(docWriteRequest, metadata); IndexRequest indexRequest = (IndexRequest) docWriteRequest; @@ -537,32 +535,30 @@ protected void doRun() { Version indexCreated = indexMetadata.getCreationVersion(); indexRequest.resolveRouting(metadata); indexRequest.process(indexCreated, mappingMd, concreteIndex.getName()); - shardId = indexRouting.indexShard( + yield indexRouting.indexShard( docWriteRequest.id(), docWriteRequest.routing(), indexRequest.getContentType(), indexRequest.source() ); - break; - case UPDATE: + } + case UPDATE -> { TransportUpdateAction.resolveAndValidateRouting( metadata, concreteIndex.getName(), (UpdateRequest) docWriteRequest ); - shardId = indexRouting.updateShard(docWriteRequest.id(), docWriteRequest.routing()); - break; - case DELETE: + yield indexRouting.updateShard(docWriteRequest.id(), docWriteRequest.routing()); + } + case DELETE -> { docWriteRequest.routing(metadata.resolveWriteIndexRouting(docWriteRequest.routing(), docWriteRequest.index())); // check if routing is required, if so, throw error if routing wasn't specified if (docWriteRequest.routing() == null && metadata.routingRequired(concreteIndex.getName())) { throw new RoutingMissingException(concreteIndex.getName(), docWriteRequest.id()); } - shardId = indexRouting.deleteShard(docWriteRequest.id(), docWriteRequest.routing()); - break; - default: - throw new AssertionError("request type not supported: [" + docWriteRequest.opType() + "]"); - } + yield indexRouting.deleteShard(docWriteRequest.id(), docWriteRequest.routing()); + } + }; List shardRequests = requestsByShard.computeIfAbsent( new ShardId(concreteIndex, shardId), shard -> new ArrayList<>() diff --git a/server/src/main/java/org/elasticsearch/action/bulk/TransportShardBulkAction.java b/server/src/main/java/org/elasticsearch/action/bulk/TransportShardBulkAction.java index 8c03506e87a41..650c103ccd1f8 100644 --- a/server/src/main/java/org/elasticsearch/action/bulk/TransportShardBulkAction.java +++ b/server/src/main/java/org/elasticsearch/action/bulk/TransportShardBulkAction.java @@ -285,23 +285,20 @@ static boolean executeBulkItemRequest( } // execute translated update request switch (updateResult.getResponseResult()) { - case CREATED: - case UPDATED: + case CREATED, UPDATED -> { IndexRequest indexRequest = updateResult.action(); IndexMetadata metadata = context.getPrimary().indexSettings().getIndexMetadata(); MappingMetadata mappingMd = metadata.mapping(); indexRequest.process(metadata.getCreationVersion(), mappingMd, updateRequest.concreteIndex()); context.setRequestToExecute(indexRequest); - break; - case DELETED: - context.setRequestToExecute(updateResult.action()); - break; - case NOOP: + } + case DELETED -> context.setRequestToExecute(updateResult.action()); + case NOOP -> { context.markOperationAsNoOp(updateResult.action()); context.markAsCompleted(context.getExecutionResult()); return true; - default: - throw new IllegalStateException("Illegal update operation " + updateResult.getResponseResult()); + } + default -> throw new IllegalStateException("Illegal update operation " + updateResult.getResponseResult()); } } else { context.setRequestToExecute(context.getCurrent()); @@ -584,8 +581,7 @@ private static Engine.Result performOpOnReplica( ) throws Exception { final Engine.Result result; switch (docWriteRequest.opType()) { - case CREATE: - case INDEX: + case CREATE, INDEX -> { final IndexRequest indexRequest = (IndexRequest) docWriteRequest; final ShardId shardId = replica.shardId(); final SourceToParse sourceToParse = new SourceToParse( @@ -604,8 +600,8 @@ private static Engine.Result performOpOnReplica( indexRequest.isRetry(), sourceToParse ); - break; - case DELETE: + } + case DELETE -> { DeleteRequest deleteRequest = (DeleteRequest) docWriteRequest; result = replica.applyDeleteOperationOnReplica( primaryResponse.getSeqNo(), @@ -613,10 +609,11 @@ private static Engine.Result performOpOnReplica( primaryResponse.getVersion(), deleteRequest.id() ); - break; - default: + } + default -> { assert false : "Unexpected request operation type on replica: " + docWriteRequest + ";primary result: " + primaryResponse; throw new IllegalStateException("Unexpected request operation type on replica: " + docWriteRequest.opType().getLowercase()); + } } if (result.getResultType() == Engine.Result.Type.MAPPING_UPDATE_REQUIRED) { // Even though the primary waits on all nodes to ack the mapping changes to the master diff --git a/server/src/main/java/org/elasticsearch/action/ingest/SimulatePipelineResponse.java b/server/src/main/java/org/elasticsearch/action/ingest/SimulatePipelineResponse.java index e1b47caac2d08..a5dc7dda64134 100644 --- a/server/src/main/java/org/elasticsearch/action/ingest/SimulatePipelineResponse.java +++ b/server/src/main/java/org/elasticsearch/action/ingest/SimulatePipelineResponse.java @@ -69,17 +69,11 @@ public class SimulatePipelineResponse extends ActionResponse implements ToXConte } } else if (token.equals(Token.START_OBJECT)) { switch (fieldName) { - case WriteableIngestDocument.DOC_FIELD: - result = new SimulateDocumentBaseResult( - WriteableIngestDocument.INGEST_DOC_PARSER.apply(parser, null).getIngestDocument() - ); - break; - case "error": - result = new SimulateDocumentBaseResult(ElasticsearchException.fromXContent(parser)); - break; - default: - parser.skipChildren(); - break; + case WriteableIngestDocument.DOC_FIELD -> result = new SimulateDocumentBaseResult( + WriteableIngestDocument.INGEST_DOC_PARSER.apply(parser, null).getIngestDocument() + ); + case "error" -> result = new SimulateDocumentBaseResult(ElasticsearchException.fromXContent(parser)); + default -> parser.skipChildren(); } } // else it is a value skip it } diff --git a/server/src/main/java/org/elasticsearch/action/search/TransportSearchAction.java b/server/src/main/java/org/elasticsearch/action/search/TransportSearchAction.java index 29e3a9589336a..aa329a153d5de 100644 --- a/server/src/main/java/org/elasticsearch/action/search/TransportSearchAction.java +++ b/server/src/main/java/org/elasticsearch/action/search/TransportSearchAction.java @@ -999,10 +999,9 @@ private void executeSearch( // disable request cache if we have only suggest searchRequest.requestCache(false); switch (searchRequest.searchType()) { - case DFS_QUERY_THEN_FETCH: + case DFS_QUERY_THEN_FETCH -> // convert to Q_T_F if we have only suggest searchRequest.searchType(QUERY_THEN_FETCH); - break; } } final DiscoveryNodes nodes = clusterState.nodes(); @@ -1192,49 +1191,42 @@ private SearchPhase searchAsyncAction( shardIterators.size(), exc -> searchTransportService.cancelSearchTask(task, "failed to merge result [" + exc.getMessage() + "]") ); - AbstractSearchAsyncAction searchAsyncAction; - switch (searchRequest.searchType()) { - case DFS_QUERY_THEN_FETCH: - searchAsyncAction = new SearchDfsQueryThenFetchAsyncAction( - logger, - searchTransportService, - connectionLookup, - aliasFilter, - concreteIndexBoosts, - searchPhaseController, - executor, - queryResultConsumer, - searchRequest, - listener, - shardIterators, - timeProvider, - clusterState, - task, - clusters - ); - break; - case QUERY_THEN_FETCH: - searchAsyncAction = new SearchQueryThenFetchAsyncAction( - logger, - searchTransportService, - connectionLookup, - aliasFilter, - concreteIndexBoosts, - searchPhaseController, - executor, - queryResultConsumer, - searchRequest, - listener, - shardIterators, - timeProvider, - clusterState, - task, - clusters - ); - break; - default: - throw new IllegalStateException("Unknown search type: [" + searchRequest.searchType() + "]"); - } + AbstractSearchAsyncAction searchAsyncAction = switch (searchRequest.searchType()) { + case DFS_QUERY_THEN_FETCH -> new SearchDfsQueryThenFetchAsyncAction( + logger, + searchTransportService, + connectionLookup, + aliasFilter, + concreteIndexBoosts, + searchPhaseController, + executor, + queryResultConsumer, + searchRequest, + listener, + shardIterators, + timeProvider, + clusterState, + task, + clusters + ); + case QUERY_THEN_FETCH -> new SearchQueryThenFetchAsyncAction( + logger, + searchTransportService, + connectionLookup, + aliasFilter, + concreteIndexBoosts, + searchPhaseController, + executor, + queryResultConsumer, + searchRequest, + listener, + shardIterators, + timeProvider, + clusterState, + task, + clusters + ); + }; return searchAsyncAction; } } diff --git a/server/src/main/java/org/elasticsearch/action/search/TransportSearchScrollAction.java b/server/src/main/java/org/elasticsearch/action/search/TransportSearchScrollAction.java index 0f8d49e3f8d39..537e98693e831 100644 --- a/server/src/main/java/org/elasticsearch/action/search/TransportSearchScrollAction.java +++ b/server/src/main/java/org/elasticsearch/action/search/TransportSearchScrollAction.java @@ -45,10 +45,19 @@ public TransportSearchScrollAction( protected void doExecute(Task task, SearchScrollRequest request, ActionListener listener) { try { ParsedScrollId scrollId = parseScrollId(request.scrollId()); - Runnable action; - switch (scrollId.getType()) { - case QUERY_THEN_FETCH_TYPE: - action = new SearchScrollQueryThenFetchAsyncAction( + Runnable action = switch (scrollId.getType()) { + case QUERY_THEN_FETCH_TYPE -> new SearchScrollQueryThenFetchAsyncAction( + logger, + clusterService, + searchTransportService, + searchPhaseController, + request, + (SearchTask) task, + scrollId, + listener + ); + case QUERY_AND_FETCH_TYPE -> // TODO can we get rid of this? + new SearchScrollQueryAndFetchAsyncAction( logger, clusterService, searchTransportService, @@ -58,22 +67,8 @@ protected void doExecute(Task task, SearchScrollRequest request, ActionListener< scrollId, listener ); - break; - case QUERY_AND_FETCH_TYPE: // TODO can we get rid of this? - action = new SearchScrollQueryAndFetchAsyncAction( - logger, - clusterService, - searchTransportService, - searchPhaseController, - request, - (SearchTask) task, - scrollId, - listener - ); - break; - default: - throw new IllegalArgumentException("Scroll id type [" + scrollId.getType() + "] unrecognized"); - } + default -> throw new IllegalArgumentException("Scroll id type [" + scrollId.getType() + "] unrecognized"); + }; action.run(); } catch (Exception e) { listener.onFailure(e); diff --git a/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java b/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java index 22367c6396360..226515ac944f5 100644 --- a/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java +++ b/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java @@ -206,14 +206,11 @@ public boolean equals(Object o) { @Override public String toString() { - switch (value) { - case ALL_ACTIVE_SHARDS: - return "ALL"; - case ACTIVE_SHARD_COUNT_DEFAULT: - return "DEFAULT"; - default: - return Integer.toString(value); - } + return switch (value) { + case ALL_ACTIVE_SHARDS -> "ALL"; + case ACTIVE_SHARD_COUNT_DEFAULT -> "DEFAULT"; + default -> Integer.toString(value); + }; } } diff --git a/server/src/main/java/org/elasticsearch/action/support/IndicesOptions.java b/server/src/main/java/org/elasticsearch/action/support/IndicesOptions.java index b7048cf243585..fbbd6b209ce9e 100644 --- a/server/src/main/java/org/elasticsearch/action/support/IndicesOptions.java +++ b/server/src/main/java/org/elasticsearch/action/support/IndicesOptions.java @@ -75,23 +75,12 @@ public static XContentBuilder toXContent(EnumSet states, XConten private static void updateSetForValue(EnumSet states, String wildcard) { switch (wildcard) { - case "open": - states.add(OPEN); - break; - case "closed": - states.add(CLOSED); - break; - case "hidden": - states.add(HIDDEN); - break; - case "none": - states.clear(); - break; - case "all": - states.addAll(EnumSet.allOf(WildcardStates.class)); - break; - default: - throw new IllegalArgumentException("No valid expand wildcard value [" + wildcard + "]"); + case "open" -> states.add(OPEN); + case "closed" -> states.add(CLOSED); + case "hidden" -> states.add(HIDDEN); + case "none" -> states.clear(); + case "all" -> states.addAll(EnumSet.allOf(WildcardStates.class)); + default -> throw new IllegalArgumentException("No valid expand wildcard value [" + wildcard + "]"); } } } diff --git a/server/src/main/java/org/elasticsearch/action/update/TransportUpdateAction.java b/server/src/main/java/org/elasticsearch/action/update/TransportUpdateAction.java index 85ca9c1ab76d1..2f172736c3de8 100644 --- a/server/src/main/java/org/elasticsearch/action/update/TransportUpdateAction.java +++ b/server/src/main/java/org/elasticsearch/action/update/TransportUpdateAction.java @@ -192,7 +192,7 @@ protected void shardOperation(final UpdateRequest request, final ActionListener< final IndexShard indexShard = indexService.getShard(shardId.getId()); final UpdateHelper.Result result = updateHelper.prepare(request, indexShard, threadPool::absoluteTimeInMillis); switch (result.getResponseResult()) { - case CREATED: + case CREATED -> { IndexRequest upsertRequest = result.action(); // we fetch it from the index request so we don't generate the bytes twice, its already done in the index request final BytesReference upsertSourceBytes = upsertRequest.source(); @@ -230,9 +230,8 @@ protected void shardOperation(final UpdateRequest request, final ActionListener< update.setForcedRefresh(response.forcedRefresh()); listener.onResponse(update); }, exception -> handleUpdateFailureWithRetry(listener, request, exception, retryCount)))); - - break; - case UPDATED: + } + case UPDATED -> { IndexRequest indexRequest = result.action(); // we fetch it from the index request so we don't generate the bytes twice, its already done in the index request final BytesReference indexSourceBytes = indexRequest.source(); @@ -261,8 +260,8 @@ protected void shardOperation(final UpdateRequest request, final ActionListener< update.setForcedRefresh(response.forcedRefresh()); listener.onResponse(update); }, exception -> handleUpdateFailureWithRetry(listener, request, exception, retryCount)))); - break; - case DELETED: + } + case DELETED -> { DeleteRequest deleteRequest = result.action(); client.bulk(toSingleItemBulkRequest(deleteRequest), wrapBulkResponse(ActionListener.wrap(response -> { UpdateResponse update = new UpdateResponse( @@ -289,8 +288,8 @@ protected void shardOperation(final UpdateRequest request, final ActionListener< update.setForcedRefresh(response.forcedRefresh()); listener.onResponse(update); }, exception -> handleUpdateFailureWithRetry(listener, request, exception, retryCount)))); - break; - case NOOP: + } + case NOOP -> { UpdateResponse update = result.action(); IndexService indexServiceOrNull = indicesService.indexService(shardId.getIndex()); if (indexServiceOrNull != null) { @@ -300,9 +299,8 @@ protected void shardOperation(final UpdateRequest request, final ActionListener< } } listener.onResponse(update); - break; - default: - throw new IllegalStateException("Illegal result " + result.getResponseResult()); + } + default -> throw new IllegalStateException("Illegal result " + result.getResponseResult()); } } diff --git a/server/src/main/java/org/elasticsearch/action/update/UpdateHelper.java b/server/src/main/java/org/elasticsearch/action/update/UpdateHelper.java index 9a0f5bcc8a47b..5ef5c9fa31bb5 100644 --- a/server/src/main/java/org/elasticsearch/action/update/UpdateHelper.java +++ b/server/src/main/java/org/elasticsearch/action/update/UpdateHelper.java @@ -126,10 +126,8 @@ Result prepareUpsert(ShardId shardId, UpdateRequest request, final GetResult get nowInMillis ); switch (upsertResult.v1()) { - case CREATE: - indexRequest = Requests.indexRequest(request.index()).source(upsertResult.v2()); - break; - case NONE: + case CREATE -> indexRequest = Requests.indexRequest(request.index()).source(upsertResult.v2()); + case NONE -> { UpdateResponse update = new UpdateResponse( shardId, getResult.getId(), @@ -140,7 +138,8 @@ Result prepareUpsert(ShardId shardId, UpdateRequest request, final GetResult get ); update.setGetResult(getResult); return new Result(update, DocWriteResponse.Result.NOOP, upsertResult.v2(), XContentType.JSON); - default: + } + default -> // It's fine to throw an exception here, the leniency is handled/logged by `executeScriptedUpsert` throw new IllegalArgumentException("unknown upsert operation, got: " + upsertResult.v1()); } @@ -258,7 +257,7 @@ Result prepareUpdateScriptRequest(ShardId shardId, UpdateRequest request, GetRes final Map updatedSourceAsMap = (Map) ctx.get(ContextFields.SOURCE); switch (operation) { - case INDEX: + case INDEX -> { final IndexRequest indexRequest = Requests.indexRequest(request.index()) .id(request.id()) .routing(routing) @@ -269,7 +268,8 @@ Result prepareUpdateScriptRequest(ShardId shardId, UpdateRequest request, GetRes .timeout(request.timeout()) .setRefreshPolicy(request.getRefreshPolicy()); return new Result(indexRequest, DocWriteResponse.Result.UPDATED, updatedSourceAsMap, updateSourceContentType); - case DELETE: + } + case DELETE -> { DeleteRequest deleteRequest = Requests.deleteRequest(request.index()) .id(request.id()) .routing(routing) @@ -279,7 +279,8 @@ Result prepareUpdateScriptRequest(ShardId shardId, UpdateRequest request, GetRes .timeout(request.timeout()) .setRefreshPolicy(request.getRefreshPolicy()); return new Result(deleteRequest, DocWriteResponse.Result.DELETED, updatedSourceAsMap, updateSourceContentType); - default: + } + default -> { // If it was neither an INDEX or DELETE operation, treat it as a noop UpdateResponse update = new UpdateResponse( shardId, @@ -302,6 +303,7 @@ Result prepareUpdateScriptRequest(ShardId shardId, UpdateRequest request, GetRes ) ); return new Result(update, DocWriteResponse.Result.NOOP, updatedSourceAsMap, updateSourceContentType); + } } } diff --git a/server/src/main/java/org/elasticsearch/bootstrap/plugins/LoggerTerminal.java b/server/src/main/java/org/elasticsearch/bootstrap/plugins/LoggerTerminal.java index 4a216a57db4cf..32e10a1bd6c66 100644 --- a/server/src/main/java/org/elasticsearch/bootstrap/plugins/LoggerTerminal.java +++ b/server/src/main/java/org/elasticsearch/bootstrap/plugins/LoggerTerminal.java @@ -69,21 +69,11 @@ public PrintWriter getErrorWriter() { @Override protected void print(Verbosity verbosity, String msg, boolean isError) { - Level level; - switch (verbosity) { - case SILENT: - level = isError ? Level.ERROR : Level.WARN; - break; - - case VERBOSE: - level = Level.DEBUG; - break; - - case NORMAL: - default: - level = isError ? Level.WARN : Level.INFO; - break; - } + Level level = switch (verbosity) { + case SILENT -> isError ? Level.ERROR : Level.WARN; + case VERBOSE -> Level.DEBUG; + case NORMAL -> isError ? Level.WARN : Level.INFO; + }; this.logger.logIfEnabled(FQCN, level, null, msg.trim(), (Throwable) null); } diff --git a/server/src/main/java/org/elasticsearch/client/Client.java b/server/src/main/java/org/elasticsearch/client/Client.java index ac4a8cb015821..968c777ff0a7e 100644 --- a/server/src/main/java/org/elasticsearch/client/Client.java +++ b/server/src/main/java/org/elasticsearch/client/Client.java @@ -73,13 +73,10 @@ public interface Client extends ElasticsearchClient, Releasable { Setting CLIENT_TYPE_SETTING_S = new Setting<>("client.type", "node", (s) -> { - switch (s) { - case "node": - case "transport": - return s; - default: - throw new IllegalArgumentException("Can't parse [client.type] must be one of [node, transport]"); - } + return switch (s) { + case "node", "transport" -> s; + default -> throw new IllegalArgumentException("Can't parse [client.type] must be one of [node, transport]"); + }; }, Property.NodeScope); /** diff --git a/server/src/main/java/org/elasticsearch/cluster/RestoreInProgress.java b/server/src/main/java/org/elasticsearch/cluster/RestoreInProgress.java index 4656ca596ed91..b7aee2500000a 100644 --- a/server/src/main/java/org/elasticsearch/cluster/RestoreInProgress.java +++ b/server/src/main/java/org/elasticsearch/cluster/RestoreInProgress.java @@ -382,18 +382,13 @@ public boolean completed() { * @return state */ public static State fromValue(byte value) { - switch (value) { - case 0: - return INIT; - case 1: - return STARTED; - case 2: - return SUCCESS; - case 3: - return FAILURE; - default: - throw new IllegalArgumentException("No snapshot state for value [" + value + "]"); - } + return switch (value) { + case 0 -> INIT; + case 1 -> STARTED; + case 2 -> SUCCESS; + case 3 -> FAILURE; + default -> throw new IllegalArgumentException("No snapshot state for value [" + value + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/cluster/SnapshotDeletionsInProgress.java b/server/src/main/java/org/elasticsearch/cluster/SnapshotDeletionsInProgress.java index c8ce4f08bfd7e..36e97fcf6dd7d 100644 --- a/server/src/main/java/org/elasticsearch/cluster/SnapshotDeletionsInProgress.java +++ b/server/src/main/java/org/elasticsearch/cluster/SnapshotDeletionsInProgress.java @@ -337,14 +337,11 @@ public enum State implements Writeable { public static State readFrom(StreamInput in) throws IOException { final byte value = in.readByte(); - switch (value) { - case 0: - return WAITING; - case 1: - return STARTED; - default: - throw new IllegalArgumentException("No snapshot delete state for value [" + value + "]"); - } + return switch (value) { + case 0 -> WAITING; + case 1 -> STARTED; + default -> throw new IllegalArgumentException("No snapshot delete state for value [" + value + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java b/server/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java index 83855f4aef876..ceacfa974328f 100644 --- a/server/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java +++ b/server/src/main/java/org/elasticsearch/cluster/SnapshotsInProgress.java @@ -408,24 +408,16 @@ public boolean failed() { } public static ShardState fromValue(byte value) { - switch (value) { - case 0: - return INIT; - case 2: - return SUCCESS; - case 3: - return FAILED; - case 4: - return ABORTED; - case 5: - return MISSING; - case 6: - return WAITING; - case 7: - return QUEUED; - default: - throw new IllegalArgumentException("No shard snapshot state for value [" + value + "]"); - } + return switch (value) { + case 0 -> INIT; + case 2 -> SUCCESS; + case 3 -> FAILED; + case 4 -> ABORTED; + case 5 -> MISSING; + case 6 -> WAITING; + case 7 -> QUEUED; + default -> throw new IllegalArgumentException("No shard snapshot state for value [" + value + "]"); + }; } } @@ -454,20 +446,14 @@ public boolean completed() { } public static State fromValue(byte value) { - switch (value) { - case 0: - return INIT; - case 1: - return STARTED; - case 2: - return SUCCESS; - case 3: - return FAILED; - case 4: - return ABORTED; - default: - throw new IllegalArgumentException("No snapshot state for value [" + value + "]"); - } + return switch (value) { + case 0 -> INIT; + case 1 -> STARTED; + case 2 -> SUCCESS; + case 3 -> FAILED; + case 4 -> ABORTED; + default -> throw new IllegalArgumentException("No snapshot state for value [" + value + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/cluster/coordination/NoMasterBlockService.java b/server/src/main/java/org/elasticsearch/cluster/coordination/NoMasterBlockService.java index 7f3642289d9ee..316daf44202c2 100644 --- a/server/src/main/java/org/elasticsearch/cluster/coordination/NoMasterBlockService.java +++ b/server/src/main/java/org/elasticsearch/cluster/coordination/NoMasterBlockService.java @@ -63,16 +63,14 @@ public NoMasterBlockService(Settings settings, ClusterSettings clusterSettings) } private static ClusterBlock parseNoMasterBlock(String value) { - switch (value) { - case "all": - return NO_MASTER_BLOCK_ALL; - case "write": - return NO_MASTER_BLOCK_WRITES; - case "metadata_write": - return NO_MASTER_BLOCK_METADATA_WRITES; - default: - throw new IllegalArgumentException("invalid no-master block [" + value + "], must be one of [all, write, metadata_write]"); - } + return switch (value) { + case "all" -> NO_MASTER_BLOCK_ALL; + case "write" -> NO_MASTER_BLOCK_WRITES; + case "metadata_write" -> NO_MASTER_BLOCK_METADATA_WRITES; + default -> throw new IllegalArgumentException( + "invalid no-master block [" + value + "], must be one of [all, write, metadata_write]" + ); + }; } public ClusterBlock getNoMasterBlock() { diff --git a/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java b/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java index 960728624ed6c..d025ddab26af6 100644 --- a/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java +++ b/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java @@ -41,16 +41,12 @@ public void writeTo(StreamOutput out) throws IOException { */ public static ClusterHealthStatus readFrom(StreamInput in) throws IOException { byte value = in.readByte(); - switch (value) { - case 0: - return GREEN; - case 1: - return YELLOW; - case 2: - return RED; - default: - throw new IllegalArgumentException("No cluster health status for value [" + value + "]"); - } + return switch (value) { + case 0 -> GREEN; + case 1 -> YELLOW; + case 2 -> RED; + default -> throw new IllegalArgumentException("No cluster health status for value [" + value + "]"); + }; } public static ClusterHealthStatus fromString(String status) { diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/DataStreamAction.java b/server/src/main/java/org/elasticsearch/cluster/metadata/DataStreamAction.java index b3c005592955d..c1913a3a7ca49 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/DataStreamAction.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/DataStreamAction.java @@ -53,14 +53,11 @@ public byte value() { } public static Type fromValue(byte value) { - switch (value) { - case 0: - return ADD_BACKING_INDEX; - case 1: - return REMOVE_BACKING_INDEX; - default: - throw new IllegalArgumentException("no data stream action type for [" + value + "]"); - } + return switch (value) { + case 0 -> ADD_BACKING_INDEX; + case 1 -> REMOVE_BACKING_INDEX; + default -> throw new IllegalArgumentException("no data stream action type for [" + value + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/Preference.java b/server/src/main/java/org/elasticsearch/cluster/routing/Preference.java index c7a2107227423..62113cdc7b0db 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/Preference.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/Preference.java @@ -59,21 +59,14 @@ public static Preference parse(String preference) { preferenceType = preference.substring(0, colonIndex); } - switch (preferenceType) { - case "_shards": - return SHARDS; - case "_prefer_nodes": - return PREFER_NODES; - case "_local": - return LOCAL; - case "_only_local": - case "_onlyLocal": - return ONLY_LOCAL; - case "_only_nodes": - return ONLY_NODES; - default: - throw new IllegalArgumentException("no Preference for [" + preferenceType + "]"); - } + return switch (preferenceType) { + case "_shards" -> SHARDS; + case "_prefer_nodes" -> PREFER_NODES; + case "_local" -> LOCAL; + case "_only_local", "_onlyLocal" -> ONLY_LOCAL; + case "_only_nodes" -> ONLY_NODES; + default -> throw new IllegalArgumentException("no Preference for [" + preferenceType + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/RecoverySource.java b/server/src/main/java/org/elasticsearch/cluster/routing/RecoverySource.java index 003b8a798fb87..d3a9cf548b068 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/RecoverySource.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/RecoverySource.java @@ -50,20 +50,13 @@ public void addAdditionalFields(XContentBuilder builder, ToXContent.Params param public static RecoverySource readFrom(StreamInput in) throws IOException { Type type = Type.values()[in.readByte()]; - switch (type) { - case EMPTY_STORE: - return EmptyStoreRecoverySource.INSTANCE; - case EXISTING_STORE: - return ExistingStoreRecoverySource.read(in); - case PEER: - return PeerRecoverySource.INSTANCE; - case SNAPSHOT: - return new SnapshotRecoverySource(in); - case LOCAL_SHARDS: - return LocalShardsRecoverySource.INSTANCE; - default: - throw new IllegalArgumentException("unknown recovery type: " + type.name()); - } + return switch (type) { + case EMPTY_STORE -> EmptyStoreRecoverySource.INSTANCE; + case EXISTING_STORE -> ExistingStoreRecoverySource.read(in); + case PEER -> PeerRecoverySource.INSTANCE; + case SNAPSHOT -> new SnapshotRecoverySource(in); + case LOCAL_SHARDS -> LocalShardsRecoverySource.INSTANCE; + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/ShardRoutingState.java b/server/src/main/java/org/elasticsearch/cluster/routing/ShardRoutingState.java index d215d197c5f7f..3d264c7a009a9 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/ShardRoutingState.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/ShardRoutingState.java @@ -46,17 +46,12 @@ public byte value() { } public static ShardRoutingState fromValue(byte value) { - switch (value) { - case 1: - return UNASSIGNED; - case 2: - return INITIALIZING; - case 3: - return STARTED; - case 4: - return RELOCATING; - default: - throw new IllegalStateException("No routing state mapped for [" + value + "]"); - } + return switch (value) { + case 1 -> UNASSIGNED; + case 2 -> INITIALIZING; + case 3 -> STARTED; + case 4 -> RELOCATING; + default -> throw new IllegalStateException("No routing state mapped for [" + value + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java b/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java index 6fd6a23715007..e7c99869a4f21 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java @@ -183,34 +183,24 @@ public void writeTo(StreamOutput out) throws IOException { public static AllocationStatus readFrom(StreamInput in) throws IOException { byte id = in.readByte(); - switch (id) { - case 0: - return DECIDERS_NO; - case 1: - return NO_VALID_SHARD_COPY; - case 2: - return DECIDERS_THROTTLED; - case 3: - return FETCHING_SHARD_DATA; - case 4: - return DELAYED_ALLOCATION; - case 5: - return NO_ATTEMPT; - default: - throw new IllegalArgumentException("Unknown AllocationStatus value [" + id + "]"); - } + return switch (id) { + case 0 -> DECIDERS_NO; + case 1 -> NO_VALID_SHARD_COPY; + case 2 -> DECIDERS_THROTTLED; + case 3 -> FETCHING_SHARD_DATA; + case 4 -> DELAYED_ALLOCATION; + case 5 -> NO_ATTEMPT; + default -> throw new IllegalArgumentException("Unknown AllocationStatus value [" + id + "]"); + }; } public static AllocationStatus fromDecision(Decision.Type decision) { Objects.requireNonNull(decision); - switch (decision) { - case NO: - return DECIDERS_NO; - case THROTTLE: - return DECIDERS_THROTTLED; - default: - throw new IllegalArgumentException("no allocation attempt from decision[" + decision + "]"); - } + return switch (decision) { + case NO -> DECIDERS_NO; + case THROTTLE -> DECIDERS_THROTTLED; + default -> throw new IllegalArgumentException("no allocation attempt from decision[" + decision + "]"); + }; } public String value() { diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationDecision.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationDecision.java index b5f5c6ba28a5b..43bb7389ad610 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationDecision.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/AllocationDecision.java @@ -74,26 +74,17 @@ public void writeTo(StreamOutput out) throws IOException { public static AllocationDecision readFrom(StreamInput in) throws IOException { byte id = in.readByte(); - switch (id) { - case 0: - return YES; - case 1: - return THROTTLED; - case 2: - return NO; - case 3: - return WORSE_BALANCE; - case 4: - return AWAITING_INFO; - case 5: - return ALLOCATION_DELAYED; - case 6: - return NO_VALID_SHARD_COPY; - case 7: - return NO_ATTEMPT; - default: - throw new IllegalArgumentException("Unknown value [" + id + "]"); - } + return switch (id) { + case 0 -> YES; + case 1 -> THROTTLED; + case 2 -> NO; + case 3 -> WORSE_BALANCE; + case 4 -> AWAITING_INFO; + case 5 -> ALLOCATION_DELAYED; + case 6 -> NO_VALID_SHARD_COPY; + case 7 -> NO_ATTEMPT; + default -> throw new IllegalArgumentException("Unknown value [" + id + "]"); + }; } /** diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/Decision.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/Decision.java index 005c26a9749f0..e84f199ddabe2 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/Decision.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/Decision.java @@ -64,14 +64,11 @@ public static Decision readFrom(StreamInput in) throws IOException { final String label = in.readOptionalString(); final String explanation = in.readOptionalString(); if (label == null && explanation == null) { - switch (type) { - case YES: - return YES; - case THROTTLE: - return THROTTLE; - case NO: - return NO; - } + return switch (type) { + case YES -> YES; + case THROTTLE -> THROTTLE; + case NO -> NO; + }; } return new Single(type, label, explanation); } @@ -94,16 +91,12 @@ public enum Type implements Writeable { public static Type readFrom(StreamInput in) throws IOException { int i = in.readVInt(); - switch (i) { - case 0: - return NO; - case 1: - return YES; - case 2: - return THROTTLE; - default: - throw new IllegalArgumentException("No Type for integer [" + i + "]"); - } + return switch (i) { + case 0 -> NO; + case 1 -> YES; + case 2 -> THROTTLE; + default -> throw new IllegalArgumentException("No Type for integer [" + i + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/common/Priority.java b/server/src/main/java/org/elasticsearch/common/Priority.java index 227c6e6b0262b..58ad9ada564b8 100644 --- a/server/src/main/java/org/elasticsearch/common/Priority.java +++ b/server/src/main/java/org/elasticsearch/common/Priority.java @@ -31,22 +31,15 @@ public static void writeTo(Priority priority, StreamOutput output) throws IOExce } public static Priority fromByte(byte b) { - switch (b) { - case 0: - return IMMEDIATE; - case 1: - return URGENT; - case 2: - return HIGH; - case 3: - return NORMAL; - case 4: - return LOW; - case 5: - return LANGUID; - default: - throw new IllegalArgumentException("can't find priority for [" + b + "]"); - } + return switch (b) { + case 0 -> IMMEDIATE; + case 1 -> URGENT; + case 2 -> HIGH; + case 3 -> NORMAL; + case 4 -> LOW; + case 5 -> LANGUID; + default -> throw new IllegalArgumentException("can't find priority for [" + b + "]"); + }; } private final byte value; diff --git a/server/src/main/java/org/elasticsearch/common/Rounding.java b/server/src/main/java/org/elasticsearch/common/Rounding.java index 00fac20be61d3..f7a28bfa0f0f3 100644 --- a/server/src/main/java/org/elasticsearch/common/Rounding.java +++ b/server/src/main/java/org/elasticsearch/common/Rounding.java @@ -200,26 +200,17 @@ public String shortName() { } public static DateTimeUnit resolve(byte id) { - switch (id) { - case 1: - return WEEK_OF_WEEKYEAR; - case 2: - return YEAR_OF_CENTURY; - case 3: - return QUARTER_OF_YEAR; - case 4: - return MONTH_OF_YEAR; - case 5: - return DAY_OF_MONTH; - case 6: - return HOUR_OF_DAY; - case 7: - return MINUTES_OF_HOUR; - case 8: - return SECOND_OF_MINUTE; - default: - throw new ElasticsearchException("Unknown date time unit id [" + id + "]"); - } + return switch (id) { + case 1 -> WEEK_OF_WEEKYEAR; + case 2 -> YEAR_OF_CENTURY; + case 3 -> QUARTER_OF_YEAR; + case 4 -> MONTH_OF_YEAR; + case 5 -> DAY_OF_MONTH; + case 6 -> HOUR_OF_DAY; + case 7 -> MINUTES_OF_HOUR; + case 8 -> SECOND_OF_MINUTE; + default -> throw new ElasticsearchException("Unknown date time unit id [" + id + "]"); + }; } } @@ -847,20 +838,14 @@ private long firstTimeOnDay(LocalDateTime localMidnight) { private LocalDateTime nextRelevantMidnight(LocalDateTime localMidnight) { assert localMidnight.toLocalTime().equals(LocalTime.MIDNIGHT) : "nextRelevantMidnight should only be called at midnight"; - switch (unit) { - case DAY_OF_MONTH: - return localMidnight.plus(1, ChronoUnit.DAYS); - case WEEK_OF_WEEKYEAR: - return localMidnight.plus(7, ChronoUnit.DAYS); - case MONTH_OF_YEAR: - return localMidnight.plus(1, ChronoUnit.MONTHS); - case QUARTER_OF_YEAR: - return localMidnight.plus(3, ChronoUnit.MONTHS); - case YEAR_OF_CENTURY: - return localMidnight.plus(1, ChronoUnit.YEARS); - default: - throw new IllegalArgumentException("Unknown round-to-midnight unit: " + unit); - } + return switch (unit) { + case DAY_OF_MONTH -> localMidnight.plus(1, ChronoUnit.DAYS); + case WEEK_OF_WEEKYEAR -> localMidnight.plus(7, ChronoUnit.DAYS); + case MONTH_OF_YEAR -> localMidnight.plus(1, ChronoUnit.MONTHS); + case QUARTER_OF_YEAR -> localMidnight.plus(3, ChronoUnit.MONTHS); + case YEAR_OF_CENTURY -> localMidnight.plus(1, ChronoUnit.YEARS); + default -> throw new IllegalArgumentException("Unknown round-to-midnight unit: " + unit); + }; } @Override @@ -1421,16 +1406,12 @@ public String toString() { public static Rounding read(StreamInput in) throws IOException { byte id = in.readByte(); - switch (id) { - case TimeUnitRounding.ID: - return new TimeUnitRounding(in); - case TimeIntervalRounding.ID: - return new TimeIntervalRounding(in); - case OffsetRounding.ID: - return new OffsetRounding(in); - default: - throw new ElasticsearchException("unknown rounding id [" + id + "]"); - } + return switch (id) { + case TimeUnitRounding.ID -> new TimeUnitRounding(in); + case TimeIntervalRounding.ID -> new TimeIntervalRounding(in); + case OffsetRounding.ID -> new OffsetRounding(in); + default -> throw new ElasticsearchException("unknown rounding id [" + id + "]"); + }; } /** diff --git a/server/src/main/java/org/elasticsearch/common/Strings.java b/server/src/main/java/org/elasticsearch/common/Strings.java index d3b739b307091..4ee307e27e533 100644 --- a/server/src/main/java/org/elasticsearch/common/Strings.java +++ b/server/src/main/java/org/elasticsearch/common/Strings.java @@ -87,23 +87,14 @@ public static List splitSmart(String s, String separator, boolean decode } ch = s.charAt(pos++); if (decode) { - switch (ch) { - case 'n': - ch = '\n'; - break; - case 't': - ch = '\t'; - break; - case 'r': - ch = '\r'; - break; - case 'b': - ch = '\b'; - break; - case 'f': - ch = '\f'; - break; - } + ch = switch (ch) { + case 'n' -> '\n'; + case 't' -> '\t'; + case 'r' -> '\r'; + case 'b' -> '\b'; + case 'f' -> '\f'; + default -> ch; + }; } } diff --git a/server/src/main/java/org/elasticsearch/common/blobstore/BlobPath.java b/server/src/main/java/org/elasticsearch/common/blobstore/BlobPath.java index 6474d5d027671..28fc9e23cd10c 100644 --- a/server/src/main/java/org/elasticsearch/common/blobstore/BlobPath.java +++ b/server/src/main/java/org/elasticsearch/common/blobstore/BlobPath.java @@ -54,14 +54,11 @@ public String buildAsString() { @Nullable public BlobPath parent() { int size = paths.size(); - switch (size) { - case 0: - return null; - case 1: - return EMPTY; - default: - return new BlobPath(List.copyOf(paths.subList(0, size - 1))); - } + return switch (size) { + case 0 -> null; + case 1 -> EMPTY; + default -> new BlobPath(List.copyOf(paths.subList(0, size - 1))); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/common/breaker/CircuitBreaker.java b/server/src/main/java/org/elasticsearch/common/breaker/CircuitBreaker.java index 0b7ba515d7dcc..9eda70259a00e 100644 --- a/server/src/main/java/org/elasticsearch/common/breaker/CircuitBreaker.java +++ b/server/src/main/java/org/elasticsearch/common/breaker/CircuitBreaker.java @@ -52,16 +52,12 @@ enum Type { NOOP; public static Type parseValue(String value) { - switch (value.toLowerCase(Locale.ROOT)) { - case "noop": - return Type.NOOP; - case "parent": - return Type.PARENT; - case "memory": - return Type.MEMORY; - default: - throw new IllegalArgumentException("No CircuitBreaker with type: " + value); - } + return switch (value.toLowerCase(Locale.ROOT)) { + case "noop" -> Type.NOOP; + case "parent" -> Type.PARENT; + case "memory" -> Type.MEMORY; + default -> throw new IllegalArgumentException("No CircuitBreaker with type: " + value); + }; } } diff --git a/server/src/main/java/org/elasticsearch/common/cache/Cache.java b/server/src/main/java/org/elasticsearch/common/cache/Cache.java index 0886881edd33d..bb4bd0062b8db 100644 --- a/server/src/main/java/org/elasticsearch/common/cache/Cache.java +++ b/server/src/main/java/org/elasticsearch/common/cache/Cache.java @@ -738,15 +738,9 @@ private void promote(Entry entry, long now) { boolean promoted = true; try (ReleasableLock ignored = lruLock.acquire()) { switch (entry.state) { - case DELETED: - promoted = false; - break; - case EXISTING: - relinkAtHead(entry); - break; - case NEW: - linkAtHead(entry); - break; + case DELETED -> promoted = false; + case EXISTING -> relinkAtHead(entry); + case NEW -> linkAtHead(entry); } if (promoted) { evict(now); diff --git a/server/src/main/java/org/elasticsearch/common/geo/GeoJson.java b/server/src/main/java/org/elasticsearch/common/geo/GeoJson.java index 80c14ce5d8e08..dc4d998438ace 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/GeoJson.java +++ b/server/src/main/java/org/elasticsearch/common/geo/GeoJson.java @@ -402,40 +402,47 @@ private static Geometry createGeometry( throw new ElasticsearchParseException("coordinates not included"); } - switch (shapeType) { - case CIRCLE: + return switch (shapeType) { + case CIRCLE -> { if (radius == null) { throw new ElasticsearchParseException("radius is not specified"); } verifyNulls(type, geometries, orientation, null); Point point = coordinates.asPoint(); - return new Circle(point.getX(), point.getY(), point.getZ(), radius.convert(DistanceUnit.METERS).value); - case POINT: + yield new Circle(point.getX(), point.getY(), point.getZ(), radius.convert(DistanceUnit.METERS).value); + } + case POINT -> { verifyNulls(type, geometries, orientation, radius); - return coordinates.asPoint(); - case MULTIPOINT: + yield coordinates.asPoint(); + } + case MULTIPOINT -> { verifyNulls(type, geometries, orientation, radius); - return coordinates.asMultiPoint(); - case LINESTRING: + yield coordinates.asMultiPoint(); + } + case LINESTRING -> { verifyNulls(type, geometries, orientation, radius); - return coordinates.asLineString(coerce); - case MULTILINESTRING: + yield coordinates.asLineString(coerce); + } + case MULTILINESTRING -> { verifyNulls(type, geometries, orientation, radius); - return coordinates.asMultiLineString(coerce); - case POLYGON: + yield coordinates.asMultiLineString(coerce); + } + case POLYGON -> { verifyNulls(type, geometries, null, radius); // handle possible null in orientation - return coordinates.asPolygon(orientation != null ? orientation : defaultOrientation, coerce); - case MULTIPOLYGON: + yield coordinates.asPolygon(orientation != null ? orientation : defaultOrientation, coerce); + } + case MULTIPOLYGON -> { verifyNulls(type, geometries, null, radius); // handle possible null in orientation - return coordinates.asMultiPolygon(orientation != null ? orientation : defaultOrientation, coerce); - case ENVELOPE: + yield coordinates.asMultiPolygon(orientation != null ? orientation : defaultOrientation, coerce); + } + case ENVELOPE -> { verifyNulls(type, geometries, orientation, radius); - return coordinates.asRectangle(); - default: - throw new ElasticsearchParseException("unsupported shape type " + type); - } + yield coordinates.asRectangle(); + } + default -> throw new ElasticsearchParseException("unsupported shape type " + type); + }; } /** @@ -516,18 +523,11 @@ private static Boolean orientationFromString(String orientation) { return null; } orientation = orientation.toLowerCase(Locale.ROOT); - switch (orientation) { - case "right": - case "counterclockwise": - case "ccw": - return true; - case "left": - case "clockwise": - case "cw": - return false; - default: - throw new IllegalArgumentException("Unknown orientation [" + orientation + "]"); - } + return switch (orientation) { + case "right", "counterclockwise", "ccw" -> true; + case "left", "clockwise", "cw" -> false; + default -> throw new IllegalArgumentException("Unknown orientation [" + orientation + "]"); + }; } public static String getGeoJsonName(Geometry geometry) { diff --git a/server/src/main/java/org/elasticsearch/common/geo/GeoPoint.java b/server/src/main/java/org/elasticsearch/common/geo/GeoPoint.java index 151be7032fece..6d654f22f24aa 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/GeoPoint.java +++ b/server/src/main/java/org/elasticsearch/common/geo/GeoPoint.java @@ -129,16 +129,12 @@ GeoPoint parseGeoHash(String geohash, EffectivePoint effectivePoint) { return resetFromGeoHash(geohash); } else { Rectangle rectangle = Geohash.toBoundingBox(geohash); - switch (effectivePoint) { - case TOP_LEFT: - return reset(rectangle.getMaxY(), rectangle.getMinX()); - case TOP_RIGHT: - return reset(rectangle.getMaxY(), rectangle.getMaxX()); - case BOTTOM_RIGHT: - return reset(rectangle.getMinY(), rectangle.getMaxX()); - default: - throw new IllegalArgumentException("Unsupported effective point " + effectivePoint); - } + return switch (effectivePoint) { + case TOP_LEFT -> reset(rectangle.getMaxY(), rectangle.getMinX()); + case TOP_RIGHT -> reset(rectangle.getMaxY(), rectangle.getMaxX()); + case BOTTOM_RIGHT -> reset(rectangle.getMinY(), rectangle.getMaxX()); + default -> throw new IllegalArgumentException("Unsupported effective point " + effectivePoint); + }; } } diff --git a/server/src/main/java/org/elasticsearch/common/geo/GeometryFormatterFactory.java b/server/src/main/java/org/elasticsearch/common/geo/GeometryFormatterFactory.java index f83730b065075..1f4ca454b9c8c 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/GeometryFormatterFactory.java +++ b/server/src/main/java/org/elasticsearch/common/geo/GeometryFormatterFactory.java @@ -27,21 +27,18 @@ public class GeometryFormatterFactory { * Returns a formatter by name */ public static Function, List> getFormatter(String name, Function toGeometry) { - switch (name) { - case GEOJSON: - return geometries -> { - final List objects = new ArrayList<>(geometries.size()); - geometries.forEach((shape) -> objects.add(GeoJson.toMap(toGeometry.apply(shape)))); - return objects; - }; - case WKT: - return geometries -> { - final List objects = new ArrayList<>(geometries.size()); - geometries.forEach((shape) -> objects.add(WellKnownText.toWKT(toGeometry.apply(shape)))); - return objects; - }; - default: - throw new IllegalArgumentException("Unrecognized geometry format [" + name + "]."); - } + return switch (name) { + case GEOJSON -> geometries -> { + final List objects = new ArrayList<>(geometries.size()); + geometries.forEach((shape) -> objects.add(GeoJson.toMap(toGeometry.apply(shape)))); + return objects; + }; + case WKT -> geometries -> { + final List objects = new ArrayList<>(geometries.size()); + geometries.forEach((shape) -> objects.add(WellKnownText.toWKT(toGeometry.apply(shape)))); + return objects; + }; + default -> throw new IllegalArgumentException("Unrecognized geometry format [" + name + "]."); + }; } } diff --git a/server/src/main/java/org/elasticsearch/common/geo/GeometryIO.java b/server/src/main/java/org/elasticsearch/common/geo/GeometryIO.java index d9c479bbf1c0d..7f2d58972f839 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/GeometryIO.java +++ b/server/src/main/java/org/elasticsearch/common/geo/GeometryIO.java @@ -137,28 +137,18 @@ private void writeCoordinates(Line line) throws IOException { public static Geometry readGeometry(StreamInput in) throws IOException { String type = in.readString(); - switch (type) { - case "geometrycollection": - return readGeometryCollection(in); - case "polygon": - return readPolygon(in); - case "point": - return readPoint(in); - case "linestring": - return readLine(in); - case "multilinestring": - return readMultiLine(in); - case "multipoint": - return readMultiPoint(in); - case "multipolygon": - return readMultiPolygon(in); - case "envelope": - return readRectangle(in); - case "circle": - return readCircle(in); - default: - throw new UnsupportedOperationException("unsupported shape type " + type); - } + return switch (type) { + case "geometrycollection" -> readGeometryCollection(in); + case "polygon" -> readPolygon(in); + case "point" -> readPoint(in); + case "linestring" -> readLine(in); + case "multilinestring" -> readMultiLine(in); + case "multipoint" -> readMultiPoint(in); + case "multipolygon" -> readMultiPolygon(in); + case "envelope" -> readRectangle(in); + case "circle" -> readCircle(in); + default -> throw new UnsupportedOperationException("unsupported shape type " + type); + }; } private static GeometryCollection readGeometryCollection(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/common/geo/GeometryParserFormat.java b/server/src/main/java/org/elasticsearch/common/geo/GeometryParserFormat.java index d0ee499607a41..b2e02b0ebdb1e 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/GeometryParserFormat.java +++ b/server/src/main/java/org/elasticsearch/common/geo/GeometryParserFormat.java @@ -80,14 +80,11 @@ public abstract Geometry fromXContent(GeometryValidator validator, boolean coerc * This method automatically recognizes the format by examining the provided {@link XContentParser}. */ public static GeometryParserFormat geometryFormat(XContentParser parser) { - switch (parser.currentToken()) { - case START_OBJECT: - case VALUE_NULL: // We don't know the format of the original geometry - so going with default - return GEOJSON; - case VALUE_STRING: - return WKT; - default: - throw new ElasticsearchParseException("shape must be an object consisting of type and coordinates"); - } + return switch (parser.currentToken()) { + // We don't know the format of the original geometry - so going with default + case START_OBJECT, VALUE_NULL -> GEOJSON; + case VALUE_STRING -> WKT; + default -> throw new ElasticsearchParseException("shape must be an object consisting of type and coordinates"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/common/geo/Orientation.java b/server/src/main/java/org/elasticsearch/common/geo/Orientation.java index 24ac324c82883..8f5712d029955 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/Orientation.java +++ b/server/src/main/java/org/elasticsearch/common/geo/Orientation.java @@ -37,17 +37,10 @@ public boolean getAsBoolean() { public static Orientation fromString(String orientation) { orientation = orientation.toLowerCase(Locale.ROOT); - switch (orientation) { - case "right": - case "counterclockwise": - case "ccw": - return Orientation.RIGHT; - case "left": - case "clockwise": - case "cw": - return Orientation.LEFT; - default: - throw new IllegalArgumentException("Unknown orientation [" + orientation + "]"); - } + return switch (orientation) { + case "right", "counterclockwise", "ccw" -> Orientation.RIGHT; + case "left", "clockwise", "cw" -> Orientation.LEFT; + default -> throw new IllegalArgumentException("Unknown orientation [" + orientation + "]"); + }; } } diff --git a/server/src/main/java/org/elasticsearch/common/geo/ShapeRelation.java b/server/src/main/java/org/elasticsearch/common/geo/ShapeRelation.java index b253829f2ed41..230fa9a695a06 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/ShapeRelation.java +++ b/server/src/main/java/org/elasticsearch/common/geo/ShapeRelation.java @@ -54,18 +54,12 @@ public static ShapeRelation getRelationByName(String name) { /** Maps ShapeRelation to Lucene's LatLonShapeRelation */ public QueryRelation getLuceneRelation() { - switch (this) { - case INTERSECTS: - return QueryRelation.INTERSECTS; - case DISJOINT: - return QueryRelation.DISJOINT; - case WITHIN: - return QueryRelation.WITHIN; - case CONTAINS: - return QueryRelation.CONTAINS; - default: - throw new IllegalArgumentException("ShapeRelation [" + this + "] not supported"); - } + return switch (this) { + case INTERSECTS -> QueryRelation.INTERSECTS; + case DISJOINT -> QueryRelation.DISJOINT; + case WITHIN -> QueryRelation.WITHIN; + case CONTAINS -> QueryRelation.CONTAINS; + }; } public String getRelationName() { diff --git a/server/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java b/server/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java index 26c15d31fa534..77aaace849c71 100644 --- a/server/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java +++ b/server/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java @@ -458,13 +458,11 @@ public String readString() throws IOException { if (offsetByteArray > 0) { sizeByteArray = sizeByteArray - offsetByteArray; switch (sizeByteArray) { // We only have 0, 1 or 2 => no need to bother with a native call to System#arrayCopy - case 1: - byteBuffer[0] = byteBuffer[offsetByteArray]; - break; - case 2: + case 1 -> byteBuffer[0] = byteBuffer[offsetByteArray]; + case 2 -> { byteBuffer[0] = byteBuffer[offsetByteArray]; byteBuffer[1] = byteBuffer[offsetByteArray + 1]; - break; + } } assert sizeByteArray <= 2 : "We never copy more than 2 bytes here since a char is 3 bytes max"; toRead = Math.min(bufferFree + offsetByteArray, minRemainingBytes); @@ -482,26 +480,11 @@ public String readString() throws IOException { for (; offsetByteArray < sizeByteArray - 2; offsetByteArray++) { final int c = byteBuffer[offsetByteArray] & 0xff; switch (c >> 4) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - charBuffer[charsOffset++] = (char) c; - break; - case 12: - case 13: - charBuffer[charsOffset++] = (char) ((c & 0x1F) << 6 | byteBuffer[++offsetByteArray] & 0x3F); - break; - case 14: - charBuffer[charsOffset++] = (char) ((c & 0x0F) << 12 | (byteBuffer[++offsetByteArray] & 0x3F) << 6 - | (byteBuffer[++offsetByteArray] & 0x3F)); - break; - default: - throwOnBrokenChar(c); + case 0, 1, 2, 3, 4, 5, 6, 7 -> charBuffer[charsOffset++] = (char) c; + case 12, 13 -> charBuffer[charsOffset++] = (char) ((c & 0x1F) << 6 | byteBuffer[++offsetByteArray] & 0x3F); + case 14 -> charBuffer[charsOffset++] = (char) ((c & 0x0F) << 12 | (byteBuffer[++offsetByteArray] & 0x3F) << 6 + | (byteBuffer[++offsetByteArray] & 0x3F)); + default -> throwOnBrokenChar(c); } } // try to extract chars from remaining bytes with bounds checks for multi-byte chars @@ -509,32 +492,23 @@ public String readString() throws IOException { for (int i = 0; i < bufferedBytesRemaining; i++) { final int c = byteBuffer[offsetByteArray] & 0xff; switch (c >> 4) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: + case 0, 1, 2, 3, 4, 5, 6, 7 -> { charBuffer[charsOffset++] = (char) c; offsetByteArray++; - break; - case 12: - case 13: + } + case 12, 13 -> { missingFromPartial = 2 - (bufferedBytesRemaining - i); if (missingFromPartial == 0) { offsetByteArray++; charBuffer[charsOffset++] = (char) ((c & 0x1F) << 6 | byteBuffer[offsetByteArray++] & 0x3F); } ++i; - break; - case 14: + } + case 14 -> { missingFromPartial = 3 - (bufferedBytesRemaining - i); ++i; - break; - default: - throwOnBrokenChar(c); + } + default -> throwOnBrokenChar(c); } } } @@ -714,70 +688,41 @@ public ImmutableOpenMap readImmutableMap(Writeable.Reader keyRea @Nullable public Object readGenericValue() throws IOException { byte type = readByte(); - switch (type) { - case -1: - return null; - case 0: - return readString(); - case 1: - return readInt(); - case 2: - return readLong(); - case 3: - return readFloat(); - case 4: - return readDouble(); - case 5: - return readBoolean(); - case 6: - return readByteArray(); - case 7: - return readArrayList(); - case 8: - return readArray(); - case 9: - return readLinkedHashMap(); - case 10: - return readHashMap(); - case 11: - return readByte(); - case 12: - return readDate(); - case 13: + return switch (type) { + case -1 -> null; + case 0 -> readString(); + case 1 -> readInt(); + case 2 -> readLong(); + case 3 -> readFloat(); + case 4 -> readDouble(); + case 5 -> readBoolean(); + case 6 -> readByteArray(); + case 7 -> readArrayList(); + case 8 -> readArray(); + case 9 -> readLinkedHashMap(); + case 10 -> readHashMap(); + case 11 -> readByte(); + case 12 -> readDate(); + case 13 -> // this used to be DateTime from Joda, and then JodaCompatibleZonedDateTime // stream-wise it is the exact same as ZonedDateTime, a timezone id and long milliseconds - return readZonedDateTime(); - case 14: - return readBytesReference(); - case 15: - return readText(); - case 16: - return readShort(); - case 17: - return readIntArray(); - case 18: - return readLongArray(); - case 19: - return readFloatArray(); - case 20: - return readDoubleArray(); - case 21: - return readBytesRef(); - case 22: - return readGeoPoint(); - case 23: - return readZonedDateTime(); - case 24: - return readCollection(StreamInput::readGenericValue, LinkedHashSet::new, Collections.emptySet()); - case 25: - return readCollection(StreamInput::readGenericValue, HashSet::new, Collections.emptySet()); - case 26: - return readBigInteger(); - case 27: - return readOffsetTime(); - default: - throw new IOException("Can't read unknown type [" + type + "]"); - } + readZonedDateTime(); + case 14 -> readBytesReference(); + case 15 -> readText(); + case 16 -> readShort(); + case 17 -> readIntArray(); + case 18 -> readLongArray(); + case 19 -> readFloatArray(); + case 20 -> readDoubleArray(); + case 21 -> readBytesRef(); + case 22 -> readGeoPoint(); + case 23 -> readZonedDateTime(); + case 24 -> readCollection(StreamInput::readGenericValue, LinkedHashSet::new, Collections.emptySet()); + case 25 -> readCollection(StreamInput::readGenericValue, HashSet::new, Collections.emptySet()); + case 26 -> readBigInteger(); + case 27 -> readOffsetTime(); + default -> throw new IOException("Can't read unknown type [" + type + "]"); + }; } /** @@ -1071,35 +1016,17 @@ public T readException() throws IOException { final String other = readOptionalString(); final String reason = readOptionalString(); readOptionalString(); // skip the msg - it's composed from file, other and reason - final Exception exception; - switch (subclass) { - case 0: - exception = new NoSuchFileException(file, other, reason); - break; - case 1: - exception = new NotDirectoryException(file); - break; - case 2: - exception = new DirectoryNotEmptyException(file); - break; - case 3: - exception = new AtomicMoveNotSupportedException(file, other, reason); - break; - case 4: - exception = new FileAlreadyExistsException(file, other, reason); - break; - case 5: - exception = new AccessDeniedException(file, other, reason); - break; - case 6: - exception = new FileSystemLoopException(file); - break; - case 7: - exception = new FileSystemException(file, other, reason); - break; - default: - throw new IllegalStateException("unknown FileSystemException with index " + subclass); - } + final Exception exception = switch (subclass) { + case 0 -> new NoSuchFileException(file, other, reason); + case 1 -> new NotDirectoryException(file); + case 2 -> new DirectoryNotEmptyException(file); + case 3 -> new AtomicMoveNotSupportedException(file, other, reason); + case 4 -> new FileAlreadyExistsException(file, other, reason); + case 5 -> new AccessDeniedException(file, other, reason); + case 6 -> new FileSystemLoopException(file); + case 7 -> new FileSystemException(file, other, reason); + default -> throw new IllegalStateException("unknown FileSystemException with index " + subclass); + }; return (T) readStackTrace(exception, this); case 14: return (T) readStackTrace(new IllegalStateException(readOptionalString(), readException()), this); diff --git a/server/src/main/java/org/elasticsearch/common/lucene/Lucene.java b/server/src/main/java/org/elasticsearch/common/lucene/Lucene.java index f857b4cb1b01a..e398b66051f79 100644 --- a/server/src/main/java/org/elasticsearch/common/lucene/Lucene.java +++ b/server/src/main/java/org/elasticsearch/common/lucene/Lucene.java @@ -471,16 +471,12 @@ private static void writeMissingValue(StreamOutput out, Object missingValue) thr private static Object readMissingValue(StreamInput in) throws IOException { final byte id = in.readByte(); - switch (id) { - case 0: - return in.readGenericValue(); - case 1: - return SortField.STRING_FIRST; - case 2: - return SortField.STRING_LAST; - default: - throw new IOException("Unknown missing value id: " + id); - } + return switch (id) { + case 0 -> in.readGenericValue(); + case 1 -> SortField.STRING_FIRST; + case 2 -> SortField.STRING_LAST; + default -> throw new IOException("Unknown missing value id: " + id); + }; } public static void writeSortValue(StreamOutput out, Object field) throws IOException { @@ -620,16 +616,12 @@ public static void writeSortField(StreamOutput out, SortField sortField) throws private static Number readExplanationValue(StreamInput in) throws IOException { final int numberType = in.readByte(); - switch (numberType) { - case 0: - return in.readFloat(); - case 1: - return in.readDouble(); - case 2: - return in.readZLong(); - default: - throw new IOException("Unexpected number type: " + numberType); - } + return switch (numberType) { + case 0 -> in.readFloat(); + case 1 -> in.readDouble(); + case 2 -> in.readZLong(); + default -> throw new IOException("Unexpected number type: " + numberType); + }; } public static Explanation readExplanation(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java b/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java index cb661cb8bf873..537ba7d318de5 100644 --- a/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java +++ b/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java @@ -53,16 +53,12 @@ private Fuzziness(String fuzziness) { * @throws IllegalArgumentException if the edit distance is not in [0, 1, 2] */ public static Fuzziness fromEdits(int edits) { - switch (edits) { - case 0: - return Fuzziness.ZERO; - case 1: - return Fuzziness.ONE; - case 2: - return Fuzziness.TWO; - default: - throw new IllegalArgumentException("Valid edit distances are [0, 1, 2] but was [" + edits + "]"); - } + return switch (edits) { + case 0 -> Fuzziness.ZERO; + case 1 -> Fuzziness.ONE; + case 2 -> Fuzziness.TWO; + default -> throw new IllegalArgumentException("Valid edit distances are [0, 1, 2] but was [" + edits + "]"); + }; } /** @@ -153,14 +149,11 @@ private static Fuzziness parseCustomAuto(final String fuzzinessString) { public static Fuzziness parse(XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); - switch (token) { - case VALUE_STRING: - return fromString(parser.text()); - case VALUE_NUMBER: - return fromEdits(parser.intValue()); - default: - throw new IllegalArgumentException("Can't parse fuzziness on token: [" + token + "]"); - } + return switch (token) { + case VALUE_STRING -> fromString(parser.text()); + case VALUE_NUMBER -> fromEdits(parser.intValue()); + default -> throw new IllegalArgumentException("Can't parse fuzziness on token: [" + token + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/env/ESFileStore.java b/server/src/main/java/org/elasticsearch/env/ESFileStore.java index 5f86c54b67987..bf777f2597d6b 100644 --- a/server/src/main/java/org/elasticsearch/env/ESFileStore.java +++ b/server/src/main/java/org/elasticsearch/env/ESFileStore.java @@ -137,15 +137,12 @@ public V getFileStoreAttributeView(Class t @Override public Object getAttribute(String attribute) throws IOException { - switch (attribute) { + return switch (attribute) { // for the partition - case "lucene:major_device_number": - return majorDeviceNumber; - case "lucene:minor_device_number": - return minorDeviceNumber; - default: - return in.getAttribute(attribute); - } + case "lucene:major_device_number" -> majorDeviceNumber; + case "lucene:minor_device_number" -> minorDeviceNumber; + default -> in.getAttribute(attribute); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/index/IndexSettings.java b/server/src/main/java/org/elasticsearch/index/IndexSettings.java index c908823ea5dc3..b1ebeb953840d 100644 --- a/server/src/main/java/org/elasticsearch/index/IndexSettings.java +++ b/server/src/main/java/org/elasticsearch/index/IndexSettings.java @@ -104,16 +104,12 @@ public final class IndexSettings { Property.IndexScope ); public static final Setting INDEX_CHECK_ON_STARTUP = new Setting<>("index.shard.check_on_startup", "false", (s) -> { - switch (s) { - case "false": - case "true": - case "checksum": - return s; - default: - throw new IllegalArgumentException( - "unknown value for [index.shard.check_on_startup] must be one of " + "[true, false, checksum] but was: " + s - ); - } + return switch (s) { + case "false", "true", "checksum" -> s; + default -> throw new IllegalArgumentException( + "unknown value for [index.shard.check_on_startup] must be one of " + "[true, false, checksum] but was: " + s + ); + }; }, Property.IndexScope); /** diff --git a/server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java b/server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java index c47c6aac0b983..a8cd6c6737048 100644 --- a/server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java +++ b/server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java @@ -849,22 +849,21 @@ private boolean canOptimizeAddDocument(Index index) { if (index.getAutoGeneratedIdTimestamp() != IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP) { assert index.getAutoGeneratedIdTimestamp() >= 0 : "autoGeneratedIdTimestamp must be positive but was: " + index.getAutoGeneratedIdTimestamp(); - switch (index.origin()) { - case PRIMARY: + return switch (index.origin()) { + case PRIMARY -> { assert assertPrimaryCanOptimizeAddDocument(index); - return true; - case PEER_RECOVERY: - case REPLICA: + yield true; + } + case PEER_RECOVERY, REPLICA -> { assert index.version() == 1 && index.versionType() == null : "version: " + index.version() + " type: " + index.versionType(); - return true; - case LOCAL_TRANSLOG_RECOVERY: - case LOCAL_RESET: + yield true; + } + case LOCAL_TRANSLOG_RECOVERY, LOCAL_RESET -> { assert index.isRetry(); - return true; // allow to optimize in order to update the max safe time stamp - default: - throw new IllegalArgumentException("unknown origin " + index.origin()); - } + yield true; // allow to optimize in order to update the max safe time stamp + } + }; } return false; } @@ -2324,14 +2323,10 @@ protected final void closeNoLock(String reason, CountDownLatch closedLatch) { @Override protected final ReferenceManager getReferenceManager(SearcherScope scope) { - switch (scope) { - case INTERNAL: - return internalReaderManager; - case EXTERNAL: - return externalReaderManager; - default: - throw new IllegalStateException("unknown scope: " + scope); - } + return switch (scope) { + case INTERNAL -> internalReaderManager; + case EXTERNAL -> externalReaderManager; + }; } private IndexWriter createWriter() throws IOException { diff --git a/server/src/main/java/org/elasticsearch/index/engine/Segment.java b/server/src/main/java/org/elasticsearch/index/engine/Segment.java index 29a6d1f2bb828..3bae0f19d1015 100644 --- a/server/src/main/java/org/elasticsearch/index/engine/Segment.java +++ b/server/src/main/java/org/elasticsearch/index/engine/Segment.java @@ -193,23 +193,13 @@ private Sort readSegmentSort(StreamInput in) throws IOException { Object missing = in.readGenericValue(); boolean max = in.readBoolean(); boolean reverse = in.readBoolean(); - final SortField.Type numericType; - switch (type) { - case 1: - numericType = SortField.Type.INT; - break; - case 2: - numericType = SortField.Type.FLOAT; - break; - case 3: - numericType = SortField.Type.DOUBLE; - break; - case 4: - numericType = SortField.Type.LONG; - break; - default: - throw new IOException("invalid index sort type:[" + type + "] for numeric field:[" + field + "]"); - } + final SortField.Type numericType = switch (type) { + case 1 -> SortField.Type.INT; + case 2 -> SortField.Type.FLOAT; + case 3 -> SortField.Type.DOUBLE; + case 4 -> SortField.Type.LONG; + default -> throw new IOException("invalid index sort type:[" + type + "] for numeric field:[" + field + "]"); + }; fields[i] = new SortedNumericSortField( field, numericType, @@ -239,20 +229,11 @@ private void writeSegmentSort(StreamOutput out, Sort sort) throws IOException { out.writeBoolean(field.getReverse()); } else if (field instanceof SortedNumericSortField) { switch (((SortedNumericSortField) field).getNumericType()) { - case INT: - out.writeByte((byte) 1); - break; - case FLOAT: - out.writeByte((byte) 2); - break; - case DOUBLE: - out.writeByte((byte) 3); - break; - case LONG: - out.writeByte((byte) 4); - break; - default: - throw new IOException("invalid index sort field:" + field); + case INT -> out.writeByte((byte) 1); + case FLOAT -> out.writeByte((byte) 2); + case DOUBLE -> out.writeByte((byte) 3); + case LONG -> out.writeByte((byte) 4); + default -> throw new IOException("invalid index sort field:" + field); } out.writeGenericValue(field.getMissingValue()); out.writeBoolean(((SortedNumericSortField) field).getSelector() == SortedNumericSelector.Type.MAX); diff --git a/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldData.java b/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldData.java index 0b86c7545bb3f..77d68919c3334 100644 --- a/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldData.java +++ b/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldData.java @@ -165,21 +165,14 @@ public static final boolean sortMissingLast(Object missingValue) { public Object missingObject(Object missingValue, boolean reversed) { if (sortMissingFirst(missingValue) || sortMissingLast(missingValue)) { final boolean min = sortMissingFirst(missingValue) ^ reversed; - switch (reducedType()) { - case INT: - return min ? Integer.MIN_VALUE : Integer.MAX_VALUE; - case LONG: - return min ? Long.MIN_VALUE : Long.MAX_VALUE; - case FLOAT: - return min ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; - case DOUBLE: - return min ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; - case STRING: - case STRING_VAL: - return null; - default: - throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType()); - } + return switch (reducedType()) { + case INT -> min ? Integer.MIN_VALUE : Integer.MAX_VALUE; + case LONG -> min ? Long.MIN_VALUE : Long.MAX_VALUE; + case FLOAT -> min ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; + case DOUBLE -> min ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; + case STRING, STRING_VAL -> null; + default -> throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType()); + }; } else { switch (reducedType()) { case INT: diff --git a/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java b/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java index ddd3cccd0a8c3..d46c239806ef8 100644 --- a/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java +++ b/server/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java @@ -36,13 +36,10 @@ public class IndexFieldDataService extends AbstractIndexComponent implements Clo FIELDDATA_CACHE_KEY, (s) -> FIELDDATA_CACHE_VALUE_NODE, (s) -> { - switch (s) { - case "node": - case "none": - return s; - default: - throw new IllegalArgumentException("failed to parse [" + s + "] must be one of [node,none]"); - } + return switch (s) { + case "node", "none" -> s; + default -> throw new IllegalArgumentException("failed to parse [" + s + "] must be one of [node,none]"); + }; }, Property.IndexScope ); diff --git a/server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedNumericIndexFieldData.java b/server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedNumericIndexFieldData.java index eb2fd2acd21de..07bb3278597fd 100644 --- a/server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedNumericIndexFieldData.java +++ b/server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedNumericIndexFieldData.java @@ -130,18 +130,13 @@ public LeafNumericFieldData load(LeafReaderContext context) { final LeafReader reader = context.reader(); final String field = fieldName; - switch (numericType) { - case HALF_FLOAT: - return new SortedNumericHalfFloatFieldData(reader, field); - case FLOAT: - return new SortedNumericFloatFieldData(reader, field); - case DOUBLE: - return new SortedNumericDoubleFieldData(reader, field); - case DATE_NANOSECONDS: - return new NanoSecondFieldData(reader, field, numericType); - default: - return new SortedNumericLongFieldData(reader, field, numericType); - } + return switch (numericType) { + case HALF_FLOAT -> new SortedNumericHalfFloatFieldData(reader, field); + case FLOAT -> new SortedNumericFloatFieldData(reader, field); + case DOUBLE -> new SortedNumericDoubleFieldData(reader, field); + case DATE_NANOSECONDS -> new NanoSecondFieldData(reader, field, numericType); + default -> new SortedNumericLongFieldData(reader, field, numericType); + }; } /** diff --git a/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java index 570aeb2feaa8a..33601a032f7ef 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java @@ -198,14 +198,11 @@ public BytesRef indexedValueForSearch(Object value) { } else { sValue = value.toString(); } - switch (sValue) { - case "true": - return Values.TRUE; - case "false": - return Values.FALSE; - default: - throw new IllegalArgumentException("Can't parse boolean value [" + sValue + "], expected [true] or [false]"); - } + return switch (sValue) { + case "true" -> Values.TRUE; + case "false" -> Values.FALSE; + default -> throw new IllegalArgumentException("Can't parse boolean value [" + sValue + "], expected [true] or [false]"); + }; } @Override @@ -213,14 +210,11 @@ public Boolean valueForDisplay(Object value) { if (value == null) { return null; } - switch (value.toString()) { - case "F": - return false; - case "T": - return true; - default: - throw new IllegalArgumentException("Expected [T] or [F] but got [" + value + "]"); - } + return switch (value.toString()) { + case "F" -> false; + case "T" -> true; + default -> throw new IllegalArgumentException("Expected [T] or [F] but got [" + value + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/index/mapper/BooleanScriptFieldType.java b/server/src/main/java/org/elasticsearch/index/mapper/BooleanScriptFieldType.java index 3ee230142009f..c67af7a030a72 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/BooleanScriptFieldType.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/BooleanScriptFieldType.java @@ -86,14 +86,11 @@ public Object valueForDisplay(Object value) { if (value == null) { return null; } - switch (value.toString()) { - case "F": - return false; - case "T": - return true; - default: - throw new IllegalArgumentException("Expected [T] or [F] but got [" + value + "]"); - } + return switch (value.toString()) { + case "F" -> false; + case "T" -> true; + default -> throw new IllegalArgumentException("Expected [T] or [F] but got [" + value + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/index/mapper/TextParams.java b/server/src/main/java/org/elasticsearch/index/mapper/TextParams.java index 9fd4699b4d683..fb59be4b38219 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/TextParams.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/TextParams.java @@ -177,36 +177,43 @@ public static Parameter termVectors(Function initia public static void setTermVectorParams(String configuration, FieldType fieldType) { switch (configuration) { - case "no": + case "no" -> { fieldType.setStoreTermVectors(false); return; - case "yes": + } + case "yes" -> { fieldType.setStoreTermVectors(true); return; - case "with_positions": + } + case "with_positions" -> { fieldType.setStoreTermVectors(true); fieldType.setStoreTermVectorPositions(true); return; - case "with_offsets": + } + case "with_offsets" -> { fieldType.setStoreTermVectors(true); fieldType.setStoreTermVectorOffsets(true); return; - case "with_positions_offsets": + } + case "with_positions_offsets" -> { fieldType.setStoreTermVectors(true); fieldType.setStoreTermVectorPositions(true); fieldType.setStoreTermVectorOffsets(true); return; - case "with_positions_payloads": + } + case "with_positions_payloads" -> { fieldType.setStoreTermVectors(true); fieldType.setStoreTermVectorPositions(true); fieldType.setStoreTermVectorPayloads(true); return; - case "with_positions_offsets_payloads": + } + case "with_positions_offsets_payloads" -> { fieldType.setStoreTermVectors(true); fieldType.setStoreTermVectorPositions(true); fieldType.setStoreTermVectorOffsets(true); fieldType.setStoreTermVectorPayloads(true); return; + } } throw new IllegalArgumentException("Unknown [term_vector] setting: [" + configuration + "]"); } diff --git a/server/src/main/java/org/elasticsearch/index/mapper/Uid.java b/server/src/main/java/org/elasticsearch/index/mapper/Uid.java index 7788d94fb24ce..a4200d851ded6 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/Uid.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/Uid.java @@ -185,13 +185,10 @@ public static String decodeId(byte[] idBytes, int offset, int length) { throw new IllegalArgumentException("Ids can't be empty"); } final int magicChar = Byte.toUnsignedInt(idBytes[offset]); - switch (magicChar) { - case NUMERIC: - return decodeNumericId(idBytes, offset, length); - case UTF8: - return decodeUtf8Id(idBytes, offset, length); - default: - return decodeBase64Id(idBytes, offset, length); - } + return switch (magicChar) { + case NUMERIC -> decodeNumericId(idBytes, offset, length); + case UTF8 -> decodeUtf8Id(idBytes, offset, length); + default -> decodeBase64Id(idBytes, offset, length); + }; } } diff --git a/server/src/main/java/org/elasticsearch/index/query/IntervalQueryBuilder.java b/server/src/main/java/org/elasticsearch/index/query/IntervalQueryBuilder.java index 9fd8ffa095f1b..6e6cec2b620ac 100644 --- a/server/src/main/java/org/elasticsearch/index/query/IntervalQueryBuilder.java +++ b/server/src/main/java/org/elasticsearch/index/query/IntervalQueryBuilder.java @@ -86,15 +86,15 @@ public static IntervalQueryBuilder fromXContent(XContentParser parser) throws IO throw new ParsingException(parser.getTokenLocation(), "Expected [FIELD_NAME] but got [" + parser.currentToken() + "]"); } switch (parser.currentName()) { - case "_name": + case "_name" -> { parser.nextToken(); name = parser.text(); - break; - case "boost": + } + case "boost" -> { parser.nextToken(); boost = parser.floatValue(); - break; - default: + } + default -> { if (providerName != null) { throw new ParsingException( parser.getTokenLocation(), @@ -103,7 +103,7 @@ public static IntervalQueryBuilder fromXContent(XContentParser parser) throws IO } providerName = parser.currentName(); provider = IntervalsSourceProvider.fromXContent(parser); - + } } } if (parser.nextToken() != XContentParser.Token.END_OBJECT) { diff --git a/server/src/main/java/org/elasticsearch/index/query/IntervalsSourceProvider.java b/server/src/main/java/org/elasticsearch/index/query/IntervalsSourceProvider.java index 261b6050debf0..8810efadbb17b 100644 --- a/server/src/main/java/org/elasticsearch/index/query/IntervalsSourceProvider.java +++ b/server/src/main/java/org/elasticsearch/index/query/IntervalsSourceProvider.java @@ -960,26 +960,17 @@ public IntervalsSource filter(IntervalsSource input, SearchExecutionContext cont return new ScriptFilterSource(input, script.getIdOrCode(), ifs); } IntervalsSource filterSource = filter.getSource(context, fieldType); - switch (type) { - case "containing": - return Intervals.containing(input, filterSource); - case "contained_by": - return Intervals.containedBy(input, filterSource); - case "not_containing": - return Intervals.notContaining(input, filterSource); - case "not_contained_by": - return Intervals.notContainedBy(input, filterSource); - case "overlapping": - return Intervals.overlapping(input, filterSource); - case "not_overlapping": - return Intervals.nonOverlapping(input, filterSource); - case "before": - return Intervals.before(input, filterSource); - case "after": - return Intervals.after(input, filterSource); - default: - throw new IllegalArgumentException("Unknown filter type [" + type + "]"); - } + return switch (type) { + case "containing" -> Intervals.containing(input, filterSource); + case "contained_by" -> Intervals.containedBy(input, filterSource); + case "not_containing" -> Intervals.notContaining(input, filterSource); + case "not_contained_by" -> Intervals.notContainedBy(input, filterSource); + case "overlapping" -> Intervals.overlapping(input, filterSource); + case "not_overlapping" -> Intervals.nonOverlapping(input, filterSource); + case "before" -> Intervals.before(input, filterSource); + case "after" -> Intervals.after(input, filterSource); + default -> throw new IllegalArgumentException("Unknown filter type [" + type + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/index/query/Operator.java b/server/src/main/java/org/elasticsearch/index/query/Operator.java index 574d4ada0b0de..45e7cbc76f891 100644 --- a/server/src/main/java/org/elasticsearch/index/query/Operator.java +++ b/server/src/main/java/org/elasticsearch/index/query/Operator.java @@ -22,25 +22,17 @@ public enum Operator implements Writeable { AND; public BooleanClause.Occur toBooleanClauseOccur() { - switch (this) { - case OR: - return BooleanClause.Occur.SHOULD; - case AND: - return BooleanClause.Occur.MUST; - default: - throw Operator.newOperatorException(this.toString()); - } + return switch (this) { + case OR -> BooleanClause.Occur.SHOULD; + case AND -> BooleanClause.Occur.MUST; + }; } public QueryParser.Operator toQueryParserOperator() { - switch (this) { - case OR: - return QueryParser.Operator.OR; - case AND: - return QueryParser.Operator.AND; - default: - throw Operator.newOperatorException(this.toString()); - } + return switch (this) { + case OR -> QueryParser.Operator.OR; + case AND -> QueryParser.Operator.AND; + }; } public static Operator readFromStream(StreamInput in) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/index/reindex/AbstractBulkByScrollRequest.java b/server/src/main/java/org/elasticsearch/index/reindex/AbstractBulkByScrollRequest.java index e3471a41ac54b..b3440aaec401a 100644 --- a/server/src/main/java/org/elasticsearch/index/reindex/AbstractBulkByScrollRequest.java +++ b/server/src/main/java/org/elasticsearch/index/reindex/AbstractBulkByScrollRequest.java @@ -205,14 +205,13 @@ public Self setAbortOnVersionConflict(boolean abortOnVersionConflict) { */ public void setConflicts(String conflicts) { switch (conflicts) { - case "proceed": + case "proceed" -> { setAbortOnVersionConflict(false); - return; - case "abort": + } + case "abort" -> { setAbortOnVersionConflict(true); - return; - default: - throw new IllegalArgumentException("conflicts may only be \"proceed\" or \"abort\" but was [" + conflicts + "]"); + } + default -> throw new IllegalArgumentException("conflicts may only be \"proceed\" or \"abort\" but was [" + conflicts + "]"); } } diff --git a/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollResponse.java b/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollResponse.java index c18f4c13f4fe6..eca77904e998f 100644 --- a/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollResponse.java +++ b/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollResponse.java @@ -230,42 +230,21 @@ private static Object parseFailure(XContentParser parser) throws IOException { parser.skipChildren(); } else if (token == Token.START_OBJECT) { switch (name) { - case SearchFailure.REASON_FIELD: - searchExc = ElasticsearchException.fromXContent(parser); - break; - case Failure.CAUSE_FIELD: - bulkExc = ElasticsearchException.fromXContent(parser); - break; - default: - parser.skipChildren(); + case SearchFailure.REASON_FIELD -> searchExc = ElasticsearchException.fromXContent(parser); + case Failure.CAUSE_FIELD -> bulkExc = ElasticsearchException.fromXContent(parser); + default -> parser.skipChildren(); } } else if (token == Token.VALUE_STRING) { switch (name) { // This field is the same as SearchFailure.index - case Failure.INDEX_FIELD: - index = parser.text(); - break; - case Failure.ID_FIELD: - id = parser.text(); - break; - case SearchFailure.NODE_FIELD: - nodeId = parser.text(); - break; - default: - // Do nothing - break; + case Failure.INDEX_FIELD -> index = parser.text(); + case Failure.ID_FIELD -> id = parser.text(); + case SearchFailure.NODE_FIELD -> nodeId = parser.text(); } } else if (token == Token.VALUE_NUMBER) { switch (name) { - case Failure.STATUS_FIELD: - status = parser.intValue(); - break; - case SearchFailure.SHARD_FIELD: - shardId = parser.intValue(); - break; - default: - // Do nothing - break; + case Failure.STATUS_FIELD -> status = parser.intValue(); + case SearchFailure.SHARD_FIELD -> shardId = parser.intValue(); } } } diff --git a/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java b/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java index cc38795c244ca..3378570ef2377 100644 --- a/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java +++ b/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java @@ -657,44 +657,18 @@ public static Status innerFromXContent(XContentParser parser) throws IOException } } else { // else if it is a value switch (fieldName) { - case Status.SLICE_ID_FIELD: - builder.setSliceId(parser.intValue()); - break; - case Status.TOTAL_FIELD: - builder.setTotal(parser.longValue()); - break; - case Status.UPDATED_FIELD: - builder.setUpdated(parser.longValue()); - break; - case Status.CREATED_FIELD: - builder.setCreated(parser.longValue()); - break; - case Status.DELETED_FIELD: - builder.setDeleted(parser.longValue()); - break; - case Status.BATCHES_FIELD: - builder.setBatches(parser.intValue()); - break; - case Status.VERSION_CONFLICTS_FIELD: - builder.setVersionConflicts(parser.longValue()); - break; - case Status.NOOPS_FIELD: - builder.setNoops(parser.longValue()); - break; - case Status.THROTTLED_RAW_FIELD: - builder.setThrottled(parser.longValue()); - break; - case Status.REQUESTS_PER_SEC_FIELD: - builder.setRequestsPerSecond(parser.floatValue()); - break; - case Status.CANCELED_FIELD: - builder.setReasonCancelled(parser.text()); - break; - case Status.THROTTLED_UNTIL_RAW_FIELD: - builder.setThrottledUntil(parser.longValue()); - break; - default: - break; + case Status.SLICE_ID_FIELD -> builder.setSliceId(parser.intValue()); + case Status.TOTAL_FIELD -> builder.setTotal(parser.longValue()); + case Status.UPDATED_FIELD -> builder.setUpdated(parser.longValue()); + case Status.CREATED_FIELD -> builder.setCreated(parser.longValue()); + case Status.DELETED_FIELD -> builder.setDeleted(parser.longValue()); + case Status.BATCHES_FIELD -> builder.setBatches(parser.intValue()); + case Status.VERSION_CONFLICTS_FIELD -> builder.setVersionConflicts(parser.longValue()); + case Status.NOOPS_FIELD -> builder.setNoops(parser.longValue()); + case Status.THROTTLED_RAW_FIELD -> builder.setThrottled(parser.longValue()); + case Status.REQUESTS_PER_SEC_FIELD -> builder.setRequestsPerSecond(parser.floatValue()); + case Status.CANCELED_FIELD -> builder.setReasonCancelled(parser.text()); + case Status.THROTTLED_UNTIL_RAW_FIELD -> builder.setThrottledUntil(parser.longValue()); } } } diff --git a/server/src/main/java/org/elasticsearch/index/reindex/ReindexRequest.java b/server/src/main/java/org/elasticsearch/index/reindex/ReindexRequest.java index bc6237829f5c9..e789d06f6c00e 100644 --- a/server/src/main/java/org/elasticsearch/index/reindex/ReindexRequest.java +++ b/server/src/main/java/org/elasticsearch/index/reindex/ReindexRequest.java @@ -123,13 +123,10 @@ private boolean routingIsValid() { if (destination.routing() == null || destination.routing().startsWith("=")) { return true; } - switch (destination.routing()) { - case "keep": - case "discard": - return true; - default: - return false; - } + return switch (destination.routing()) { + case "keep", "discard" -> true; + default -> false; + }; } /** diff --git a/server/src/main/java/org/elasticsearch/index/search/MatchQueryParser.java b/server/src/main/java/org/elasticsearch/index/search/MatchQueryParser.java index e796ada46a85e..a5b3cd6317ec4 100644 --- a/server/src/main/java/org/elasticsearch/index/search/MatchQueryParser.java +++ b/server/src/main/java/org/elasticsearch/index/search/MatchQueryParser.java @@ -234,23 +234,12 @@ public Query parse(Type type, String fieldName, Object value) throws IOException } } - Query query; - switch (type) { - case BOOLEAN: - query = builder.createBooleanQuery(resolvedFieldName, stringValue, occur); - break; - case BOOLEAN_PREFIX: - query = builder.createBooleanPrefixQuery(resolvedFieldName, stringValue, occur); - break; - case PHRASE: - query = builder.createPhraseQuery(resolvedFieldName, stringValue, phraseSlop); - break; - case PHRASE_PREFIX: - query = builder.createPhrasePrefixQuery(resolvedFieldName, stringValue, phraseSlop); - break; - default: - throw new IllegalStateException("No type found for [" + type + "]"); - } + Query query = switch (type) { + case BOOLEAN -> builder.createBooleanQuery(resolvedFieldName, stringValue, occur); + case BOOLEAN_PREFIX -> builder.createBooleanPrefixQuery(resolvedFieldName, stringValue, occur); + case PHRASE -> builder.createPhraseQuery(resolvedFieldName, stringValue, phraseSlop); + case PHRASE_PREFIX -> builder.createPhrasePrefixQuery(resolvedFieldName, stringValue, phraseSlop); + }; return query == null ? zeroTermsQuery.asQuery() : query; } diff --git a/server/src/main/java/org/elasticsearch/index/search/MultiMatchQueryParser.java b/server/src/main/java/org/elasticsearch/index/search/MultiMatchQueryParser.java index 8db95af925b65..0fb9e2e4c1a4a 100644 --- a/server/src/main/java/org/elasticsearch/index/search/MultiMatchQueryParser.java +++ b/server/src/main/java/org/elasticsearch/index/search/MultiMatchQueryParser.java @@ -55,23 +55,15 @@ public Query parse(MultiMatchQueryBuilder.Type type, Map fieldNam return Queries.newUnmappedFieldsQuery(fieldNames.keySet()); } final float tieBreaker = groupTieBreaker == null ? type.tieBreaker() : groupTieBreaker; - final List queries; - switch (type) { - case PHRASE: - case PHRASE_PREFIX: - case BEST_FIELDS: - case MOST_FIELDS: - case BOOL_PREFIX: - queries = buildFieldQueries(type, fieldNames, value, minimumShouldMatch); - break; - - case CROSS_FIELDS: - queries = buildCrossFieldQuery(fieldNames, value, minimumShouldMatch, tieBreaker); - break; - - default: - throw new IllegalStateException("No such type: " + type); - } + final List queries = switch (type) { + case PHRASE, PHRASE_PREFIX, BEST_FIELDS, MOST_FIELDS, BOOL_PREFIX -> buildFieldQueries( + type, + fieldNames, + value, + minimumShouldMatch + ); + case CROSS_FIELDS -> buildCrossFieldQuery(fieldNames, value, minimumShouldMatch, tieBreaker); + }; return combineGrouped(queries, tieBreaker); } diff --git a/server/src/main/java/org/elasticsearch/index/shard/IndexLongFieldRange.java b/server/src/main/java/org/elasticsearch/index/shard/IndexLongFieldRange.java index 15286651d6608..02ba431cdcb61 100644 --- a/server/src/main/java/org/elasticsearch/index/shard/IndexLongFieldRange.java +++ b/server/src/main/java/org/elasticsearch/index/shard/IndexLongFieldRange.java @@ -135,18 +135,13 @@ public void writeTo(StreamOutput out) throws IOException { public static IndexLongFieldRange readFrom(StreamInput in) throws IOException { final byte type = in.readByte(); - switch (type) { - case WIRE_TYPE_NO_SHARDS: - return NO_SHARDS; - case WIRE_TYPE_UNKNOWN: - return UNKNOWN; - case WIRE_TYPE_EMPTY: - return EMPTY; - case WIRE_TYPE_OTHER: - return new IndexLongFieldRange(in.readBoolean() ? in.readVIntArray() : null, in.readZLong(), in.readZLong()); - default: - throw new IllegalStateException("type [" + type + "] not known"); - } + return switch (type) { + case WIRE_TYPE_NO_SHARDS -> NO_SHARDS; + case WIRE_TYPE_UNKNOWN -> UNKNOWN; + case WIRE_TYPE_EMPTY -> EMPTY; + case WIRE_TYPE_OTHER -> new IndexLongFieldRange(in.readBoolean() ? in.readVIntArray() : null, in.readZLong(), in.readZLong()); + default -> throw new IllegalStateException("type [" + type + "] not known"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java b/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java index 8703f72dc8952..2e98d8f439497 100644 --- a/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java +++ b/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java @@ -1784,7 +1784,7 @@ private Engine.Result applyTranslogOperation(Engine engine, Translog.Operation o final VersionType versionType = (origin == Engine.Operation.Origin.PRIMARY) ? VersionType.EXTERNAL : null; final Engine.Result result; switch (operation.opType()) { - case INDEX: + case INDEX -> { final Translog.Index index = (Translog.Index) operation; // we set canHaveDuplicates to true all the time such that we de-optimze the translog case and ensure that all // autoGeneratedID docs that are coming from the primary are updated correctly. @@ -1808,8 +1808,8 @@ private Engine.Result applyTranslogOperation(Engine engine, Translog.Operation o Map.of() ) ); - break; - case DELETE: + } + case DELETE -> { final Translog.Delete delete = (Translog.Delete) operation; result = applyDeleteOperation( engine, @@ -1822,13 +1822,12 @@ private Engine.Result applyTranslogOperation(Engine engine, Translog.Operation o 0, origin ); - break; - case NO_OP: + } + case NO_OP -> { final Translog.NoOp noOp = (Translog.NoOp) operation; result = markSeqNoAsNoop(engine, noOp.seqNo(), noOp.primaryTerm(), noOp.reason(), origin); - break; - default: - throw new IllegalStateException("No operation defined for [" + operation + "]"); + } + default -> throw new IllegalStateException("No operation defined for [" + operation + "]"); } return result; } diff --git a/server/src/main/java/org/elasticsearch/index/shard/ShardLongFieldRange.java b/server/src/main/java/org/elasticsearch/index/shard/ShardLongFieldRange.java index ca2d311d118ec..107848fda5654 100644 --- a/server/src/main/java/org/elasticsearch/index/shard/ShardLongFieldRange.java +++ b/server/src/main/java/org/elasticsearch/index/shard/ShardLongFieldRange.java @@ -78,16 +78,12 @@ public String toString() { public static ShardLongFieldRange readFrom(StreamInput in) throws IOException { final byte type = in.readByte(); - switch (type) { - case WIRE_TYPE_UNKNOWN: - return UNKNOWN; - case WIRE_TYPE_EMPTY: - return EMPTY; - case WIRE_TYPE_OTHER: - return ShardLongFieldRange.of(in.readZLong(), in.readZLong()); - default: - throw new IllegalStateException("type [" + type + "] not known"); - } + return switch (type) { + case WIRE_TYPE_UNKNOWN -> UNKNOWN; + case WIRE_TYPE_EMPTY -> EMPTY; + case WIRE_TYPE_OTHER -> ShardLongFieldRange.of(in.readZLong(), in.readZLong()); + default -> throw new IllegalStateException("type [" + type + "] not known"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/index/shard/ShardSplittingQuery.java b/server/src/main/java/org/elasticsearch/index/shard/ShardSplittingQuery.java index 0cfd29fad1193..df95df33f71c6 100644 --- a/server/src/main/java/org/elasticsearch/index/shard/ShardSplittingQuery.java +++ b/server/src/main/java/org/elasticsearch/index/shard/ShardSplittingQuery.java @@ -227,22 +227,16 @@ private final class Visitor extends StoredFieldVisitor { @Override public void binaryField(FieldInfo fieldInfo, byte[] value) throws IOException { switch (fieldInfo.name) { - case IdFieldMapper.NAME: - id = Uid.decodeId(value); - break; - default: - throw new IllegalStateException("Unexpected field: " + fieldInfo.name); + case IdFieldMapper.NAME -> id = Uid.decodeId(value); + default -> throw new IllegalStateException("Unexpected field: " + fieldInfo.name); } } @Override public void stringField(FieldInfo fieldInfo, String value) throws IOException { switch (fieldInfo.name) { - case RoutingFieldMapper.NAME: - routing = value; - break; - default: - throw new IllegalStateException("Unexpected field: " + fieldInfo.name); + case RoutingFieldMapper.NAME -> routing = value; + default -> throw new IllegalStateException("Unexpected field: " + fieldInfo.name); } } diff --git a/server/src/main/java/org/elasticsearch/index/store/FsDirectoryFactory.java b/server/src/main/java/org/elasticsearch/index/store/FsDirectoryFactory.java index db7a122de4944..b5fcd92763dc0 100644 --- a/server/src/main/java/org/elasticsearch/index/store/FsDirectoryFactory.java +++ b/server/src/main/java/org/elasticsearch/index/store/FsDirectoryFactory.java @@ -36,14 +36,11 @@ public class FsDirectoryFactory implements IndexStorePlugin.DirectoryFactory { public static final Setting INDEX_LOCK_FACTOR_SETTING = new Setting<>("index.store.fs.fs_lock", "native", (s) -> { - switch (s) { - case "native": - return NativeFSLockFactory.INSTANCE; - case "simple": - return SimpleFSLockFactory.INSTANCE; - default: - throw new IllegalArgumentException("unrecognized [index.store.fs.fs_lock] \"" + s + "\": must be native or simple"); - } // can we set on both - node and index level, some nodes might be running on NFS so they might need simple rather than native + return switch (s) { + case "native" -> NativeFSLockFactory.INSTANCE; + case "simple" -> SimpleFSLockFactory.INSTANCE; + default -> throw new IllegalArgumentException("unrecognized [index.store.fs.fs_lock] \"" + s + "\": must be native or simple"); + }; // can we set on both - node and index level, some nodes might be running on NFS so they might need simple rather than native }, Property.IndexScope, Property.NodeScope); @Override diff --git a/server/src/main/java/org/elasticsearch/index/translog/Translog.java b/server/src/main/java/org/elasticsearch/index/translog/Translog.java index 7cd8d5701192c..ac01dc0c494f6 100644 --- a/server/src/main/java/org/elasticsearch/index/translog/Translog.java +++ b/server/src/main/java/org/elasticsearch/index/translog/Translog.java @@ -1079,18 +1079,13 @@ public byte id() { } public static Type fromId(byte id) { - switch (id) { - case 1: - return CREATE; - case 2: - return INDEX; - case 3: - return DELETE; - case 4: - return NO_OP; - default: - throw new IllegalArgumentException("no type mapped for [" + id + "]"); - } + return switch (id) { + case 1 -> CREATE; + case 2 -> INDEX; + case 3 -> DELETE; + case 4 -> NO_OP; + default -> throw new IllegalArgumentException("no type mapped for [" + id + "]"); + }; } } @@ -1110,18 +1105,12 @@ public static Type fromId(byte id) { */ static Operation readOperation(final StreamInput input) throws IOException { final Translog.Operation.Type type = Translog.Operation.Type.fromId(input.readByte()); - switch (type) { - case CREATE: - // the de-serialization logic in Index was identical to that of Create when create was deprecated - case INDEX: - return new Index(input); - case DELETE: - return new Delete(input); - case NO_OP: - return new NoOp(input); - default: - throw new AssertionError("no case for [" + type + "]"); - } + return switch (type) { + // the de-serialization logic in Index was identical to that of Create when create was deprecated + case CREATE, INDEX -> new Index(input); + case DELETE -> new Delete(input); + case NO_OP -> new NoOp(input); + }; } /** @@ -1130,19 +1119,11 @@ static Operation readOperation(final StreamInput input) throws IOException { static void writeOperation(final StreamOutput output, final Operation operation) throws IOException { output.writeByte(operation.opType().id()); switch (operation.opType()) { - case CREATE: - // the serialization logic in Index was identical to that of Create when create was deprecated - case INDEX: - ((Index) operation).write(output); - break; - case DELETE: - ((Delete) operation).write(output); - break; - case NO_OP: - ((NoOp) operation).write(output); - break; - default: - throw new AssertionError("no case for [" + operation.opType() + "]"); + // the serialization logic in Index was identical to that of Create when create was deprecated + case CREATE, INDEX -> ((Index) operation).write(output); + case DELETE -> ((Delete) operation).write(output); + case NO_OP -> ((NoOp) operation).write(output); + default -> throw new AssertionError("no case for [" + operation.opType() + "]"); } } diff --git a/server/src/main/java/org/elasticsearch/indices/IndicesService.java b/server/src/main/java/org/elasticsearch/indices/IndicesService.java index 47c9d359ce8b1..e35c714f60bd5 100644 --- a/server/src/main/java/org/elasticsearch/indices/IndicesService.java +++ b/server/src/main/java/org/elasticsearch/indices/IndicesService.java @@ -435,30 +435,14 @@ public NodeIndicesStats stats(CommonStatsFlags flags) { // the cumulative statistics also account for shards that are no longer on this node, which is tracked by oldShardsStats for (Flag flag : flags.getFlags()) { switch (flag) { - case Get: - commonStats.get.add(oldShardsStats.getStats); - break; - case Indexing: - commonStats.indexing.add(oldShardsStats.indexingStats); - break; - case Search: - commonStats.search.add(oldShardsStats.searchStats); - break; - case Merge: - commonStats.merge.add(oldShardsStats.mergeStats); - break; - case Refresh: - commonStats.refresh.add(oldShardsStats.refreshStats); - break; - case Recovery: - commonStats.recoveryStats.add(oldShardsStats.recoveryStats); - break; - case Flush: - commonStats.flush.add(oldShardsStats.flushStats); - break; - case Bulk: - commonStats.bulk.add(oldShardsStats.bulkStats); - break; + case Get -> commonStats.get.add(oldShardsStats.getStats); + case Indexing -> commonStats.indexing.add(oldShardsStats.indexingStats); + case Search -> commonStats.search.add(oldShardsStats.searchStats); + case Merge -> commonStats.merge.add(oldShardsStats.mergeStats); + case Refresh -> commonStats.refresh.add(oldShardsStats.refreshStats); + case Recovery -> commonStats.recoveryStats.add(oldShardsStats.recoveryStats); + case Flush -> commonStats.flush.add(oldShardsStats.flushStats); + case Bulk -> commonStats.bulk.add(oldShardsStats.bulkStats); } } diff --git a/server/src/main/java/org/elasticsearch/indices/analysis/AnalysisModule.java b/server/src/main/java/org/elasticsearch/indices/analysis/AnalysisModule.java index 564d6e2bf19fa..865617e1ddb7a 100644 --- a/server/src/main/java/org/elasticsearch/indices/analysis/AnalysisModule.java +++ b/server/src/main/java/org/elasticsearch/indices/analysis/AnalysisModule.java @@ -226,14 +226,10 @@ static Map setupPreConfiguredTokenizers(List tokenizer.create(Version.CURRENT)); - break; - default: - throw new UnsupportedOperationException("Caching strategy unsupported by temporary shim [" + tokenizer + "]"); - } + PreConfiguredTokenizer preConfigured = switch (tokenizer.getCachingStrategy()) { + case ONE -> PreConfiguredTokenizer.singleton(name, () -> tokenizer.create(Version.CURRENT)); + default -> throw new UnsupportedOperationException("Caching strategy unsupported by temporary shim [" + tokenizer + "]"); + }; preConfiguredTokenizers.register(name, preConfigured); } for (AnalysisPlugin plugin : plugins) { diff --git a/server/src/main/java/org/elasticsearch/indices/analysis/PreBuiltCacheFactory.java b/server/src/main/java/org/elasticsearch/indices/analysis/PreBuiltCacheFactory.java index aef3780c564c5..91bc073cfecdf 100644 --- a/server/src/main/java/org/elasticsearch/indices/analysis/PreBuiltCacheFactory.java +++ b/server/src/main/java/org/elasticsearch/indices/analysis/PreBuiltCacheFactory.java @@ -7,7 +7,6 @@ */ package org.elasticsearch.indices.analysis; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import java.util.Collection; @@ -43,16 +42,11 @@ public interface PreBuiltCache { private PreBuiltCacheFactory() {} public static PreBuiltCache getCache(CachingStrategy cachingStrategy) { - switch (cachingStrategy) { - case ONE: - return new PreBuiltCacheStrategyOne<>(); - case LUCENE: - return new PreBuiltCacheStrategyLucene<>(); - case ELASTICSEARCH: - return new PreBuiltCacheStrategyElasticsearch<>(); - default: - throw new ElasticsearchException("No action configured for caching strategy[" + cachingStrategy + "]"); - } + return switch (cachingStrategy) { + case ONE -> new PreBuiltCacheStrategyOne<>(); + case LUCENE -> new PreBuiltCacheStrategyLucene<>(); + case ELASTICSEARCH -> new PreBuiltCacheStrategyElasticsearch<>(); + }; } /** 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 2085168f475cd..080367d4c638b 100644 --- a/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java +++ b/server/src/main/java/org/elasticsearch/indices/recovery/RecoveryState.java @@ -181,38 +181,37 @@ public synchronized void validateCurrentStage(Stage expected) { // synchronized is strictly speaking not needed (this is called by a single thread), but just to be safe public synchronized RecoveryState setStage(Stage stage) { switch (stage) { - case INIT: + case INIT -> { // reinitializing stop remove all state except for start time this.stage = Stage.INIT; getIndex().reset(); getVerifyIndex().reset(); getTranslog().reset(); - break; - case INDEX: + } + case INDEX -> { validateAndSetStage(Stage.INIT, stage); getIndex().start(); - break; - case VERIFY_INDEX: + } + case VERIFY_INDEX -> { validateAndSetStage(Stage.INDEX, stage); getIndex().stop(); getVerifyIndex().start(); - break; - case TRANSLOG: + } + case TRANSLOG -> { validateAndSetStage(Stage.VERIFY_INDEX, stage); getVerifyIndex().stop(); getTranslog().start(); - break; - case FINALIZE: + } + case FINALIZE -> { assert getIndex().bytesStillToRecover() >= 0 : "moving to stage FINALIZE without completing file details"; validateAndSetStage(Stage.TRANSLOG, stage); getTranslog().stop(); - break; - case DONE: + } + case DONE -> { validateAndSetStage(Stage.FINALIZE, stage); getTimer().stop(); - break; - default: - throw new IllegalArgumentException("unknown RecoveryState.Stage [" + stage + "]"); + } + default -> throw new IllegalArgumentException("unknown RecoveryState.Stage [" + stage + "]"); } return this; } diff --git a/server/src/main/java/org/elasticsearch/lucene/grouping/GroupingDocValuesSelector.java b/server/src/main/java/org/elasticsearch/lucene/grouping/GroupingDocValuesSelector.java index c86a6bafab205..9175aa3b7f2a5 100644 --- a/server/src/main/java/org/elasticsearch/lucene/grouping/GroupingDocValuesSelector.java +++ b/server/src/main/java/org/elasticsearch/lucene/grouping/GroupingDocValuesSelector.java @@ -86,11 +86,8 @@ public void setNextReader(LeafReaderContext readerContext) throws IOException { return; } switch (type) { - case NUMERIC: - values = DocValues.getNumeric(reader, field); - break; - - case SORTED_NUMERIC: + case NUMERIC -> values = DocValues.getNumeric(reader, field); + case SORTED_NUMERIC -> { final SortedNumericDocValues sorted = DocValues.getSortedNumeric(reader, field); values = DocValues.unwrapSingleton(sorted); if (values == null) { @@ -125,10 +122,8 @@ public long longValue() throws IOException { }; } - break; - - default: - throw new IllegalStateException("unexpected doc values type " + type + "` for field `" + field + "`"); + } + default -> throw new IllegalStateException("unexpected doc values type " + type + "` for field `" + field + "`"); } } @@ -191,11 +186,8 @@ public void setNextReader(LeafReaderContext readerContext) throws IOException { return; } switch (type) { - case SORTED: - values = DocValues.getSorted(reader, field); - break; - - case SORTED_SET: + case SORTED -> values = DocValues.getSorted(reader, field); + case SORTED_SET -> { final SortedSetDocValues sorted = DocValues.getSortedSet(reader, field); values = DocValues.unwrapSingleton(sorted); if (values == null) { @@ -239,10 +231,8 @@ public int getValueCount() { } }; } - break; - - default: - throw new IllegalStateException("unexpected doc values type " + type + "` for field `" + field + "`"); + } + default -> throw new IllegalStateException("unexpected doc values type " + type + "` for field `" + field + "`"); } } diff --git a/server/src/main/java/org/elasticsearch/monitor/jvm/HotThreads.java b/server/src/main/java/org/elasticsearch/monitor/jvm/HotThreads.java index a2b2ba7b30db6..a355f769028f4 100644 --- a/server/src/main/java/org/elasticsearch/monitor/jvm/HotThreads.java +++ b/server/src/main/java/org/elasticsearch/monitor/jvm/HotThreads.java @@ -307,17 +307,15 @@ String innerDetect(ThreadMXBean threadBean, SunThreadInfo sunThreadInfo, long cu ThreadTimeAccumulator topThread = topThreads.get(t); switch (type) { - case MEM: - sb.append( - String.format( - Locale.ROOT, - "%n%s memory allocated by thread '%s'%n", - new ByteSizeValue(topThread.getAllocatedBytes()), - threadName - ) - ); - break; - case CPU: + case MEM -> sb.append( + String.format( + Locale.ROOT, + "%n%s memory allocated by thread '%s'%n", + new ByteSizeValue(topThread.getAllocatedBytes()), + threadName + ) + ); + case CPU -> { double percentCpu = getTimeSharePercentage(topThread.getCpuTime()); double percentOther = getTimeSharePercentage(topThread.getOtherTime()); sb.append( @@ -333,8 +331,8 @@ String innerDetect(ThreadMXBean threadBean, SunThreadInfo sunThreadInfo, long cu threadName ) ); - break; - default: + } + default -> { long time = ThreadTimeAccumulator.valueGetterForReportType(type).applyAsLong(topThread); double percent = getTimeSharePercentage(time); sb.append( @@ -348,7 +346,7 @@ String innerDetect(ThreadMXBean threadBean, SunThreadInfo sunThreadInfo, long cu threadName ) ); - break; + } } // for each snapshot (2nd array index) find later snapshot for same thread with max number of @@ -495,17 +493,12 @@ public long getThreadId() { } static ToLongFunction valueGetterForReportType(ReportType type) { - switch (type) { - case CPU: - return ThreadTimeAccumulator::getCpuTime; - case WAIT: - return ThreadTimeAccumulator::getWaitedTime; - case BLOCK: - return ThreadTimeAccumulator::getBlockedTime; - case MEM: - return ThreadTimeAccumulator::getAllocatedBytes; - } - throw new IllegalArgumentException("expected thread type to be either 'cpu', 'wait', 'mem', or 'block', but was " + type); + return switch (type) { + case CPU -> ThreadTimeAccumulator::getCpuTime; + case WAIT -> ThreadTimeAccumulator::getWaitedTime; + case BLOCK -> ThreadTimeAccumulator::getBlockedTime; + case MEM -> ThreadTimeAccumulator::getAllocatedBytes; + }; } } diff --git a/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java b/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java index 5b27bcee28d33..6062e7fb45b2b 100644 --- a/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java +++ b/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java @@ -441,15 +441,9 @@ private OsStats.Cgroup.CpuStat getCgroupCpuAcctCpuStat(final String controlGroup for (final String line : lines) { final String[] fields = line.split("\\s+"); switch (fields[0]) { - case "nr_periods": - numberOfPeriods = Long.parseLong(fields[1]); - break; - case "nr_throttled": - numberOfTimesThrottled = Long.parseLong(fields[1]); - break; - case "throttled_time": - timeThrottledNanos = Long.parseLong(fields[1]); - break; + case "nr_periods" -> numberOfPeriods = Long.parseLong(fields[1]); + case "nr_throttled" -> numberOfTimesThrottled = Long.parseLong(fields[1]); + case "throttled_time" -> timeThrottledNanos = Long.parseLong(fields[1]); } } assert numberOfPeriods != -1; diff --git a/server/src/main/java/org/elasticsearch/node/Node.java b/server/src/main/java/org/elasticsearch/node/Node.java index 38ff33abd0f2f..a7f62ea6ca0ff 100644 --- a/server/src/main/java/org/elasticsearch/node/Node.java +++ b/server/src/main/java/org/elasticsearch/node/Node.java @@ -235,13 +235,10 @@ public class Node implements Closeable { }, Property.NodeScope) ); public static final Setting BREAKER_TYPE_KEY = new Setting<>("indices.breaker.type", "hierarchy", (s) -> { - switch (s) { - case "hierarchy": - case "none": - return s; - default: - throw new IllegalArgumentException("indices.breaker.type must be one of [hierarchy, none] but was: " + s); - } + return switch (s) { + case "hierarchy", "none" -> s; + default -> throw new IllegalArgumentException("indices.breaker.type must be one of [hierarchy, none] but was: " + s); + }; }, Setting.Property.NodeScope); public static final Setting INITIAL_STATE_TIMEOUT_SETTING = Setting.positiveTimeSetting( diff --git a/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java b/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java index 985b4408a00d3..001f49ad91784 100644 --- a/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java +++ b/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java @@ -789,17 +789,13 @@ public static RepositoryData snapshotsFromXContent(XContentParser parser, long g while (parser.nextToken() == XContentParser.Token.FIELD_NAME) { final String field = parser.currentName(); switch (field) { - case SNAPSHOTS: - parseSnapshots(parser, snapshots, snapshotsDetails, indexMetaLookup); - break; - case INDICES: - parseIndices(parser, fixBrokenShardGens, snapshots, indexSnapshots, indexLookup, shardGenerations); - break; - case INDEX_METADATA_IDENTIFIERS: + case SNAPSHOTS -> parseSnapshots(parser, snapshots, snapshotsDetails, indexMetaLookup); + case INDICES -> parseIndices(parser, fixBrokenShardGens, snapshots, indexSnapshots, indexLookup, shardGenerations); + case INDEX_METADATA_IDENTIFIERS -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser); indexMetaIdentifiers = parser.mapStrings(); - break; - case MIN_VERSION: + } + case MIN_VERSION -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.nextToken(), parser); final Version version = Version.fromString(parser.text()); assert SnapshotsService.useShardGenerations(version); @@ -808,19 +804,18 @@ public static RepositoryData snapshotsFromXContent(XContentParser parser, long g "this snapshot repository format requires Elasticsearch version [" + version + "] or later" ); } - break; - case UUID: + } + case UUID -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.nextToken(), parser); uuid = parser.text(); assert uuid.equals(MISSING_UUID) == false; - break; - case CLUSTER_UUID: + } + case CLUSTER_UUID -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.nextToken(), parser); clusterUUID = parser.text(); assert clusterUUID.equals(MISSING_UUID) == false; - break; - default: - XContentParserUtils.throwUnknownField(field, parser.getTokenLocation()); + } + default -> XContentParserUtils.throwUnknownField(field, parser.getTokenLocation()); } } @@ -901,31 +896,23 @@ private static void parseSnapshots( String currentFieldName = parser.currentName(); parser.nextToken(); switch (currentFieldName) { - case NAME: - name = parser.text(); - break; - case UUID: - uuid = parser.text(); - break; - case STATE: - state = SnapshotState.fromValue((byte) parser.intValue()); - break; - case INDEX_METADATA_LOOKUP: - metaGenerations = parser.map(HashMap::new, p -> stringDeduplicator.computeIfAbsent(p.text(), Function.identity())); - break; - case VERSION: - version = Version.fromString(parser.text()); - break; - case START_TIME_MILLIS: + case NAME -> name = parser.text(); + case UUID -> uuid = parser.text(); + case STATE -> state = SnapshotState.fromValue((byte) parser.intValue()); + case INDEX_METADATA_LOOKUP -> metaGenerations = parser.map( + HashMap::new, + p -> stringDeduplicator.computeIfAbsent(p.text(), Function.identity()) + ); + case VERSION -> version = Version.fromString(parser.text()); + case START_TIME_MILLIS -> { assert startTimeMillis == -1; startTimeMillis = parser.longValue(); - break; - case END_TIME_MILLIS: + } + case END_TIME_MILLIS -> { assert endTimeMillis == -1; endTimeMillis = parser.longValue(); - break; - case SLM_POLICY: - slmPolicy = stringDeduplicator.computeIfAbsent(parser.text(), Function.identity()); + } + case SLM_POLICY -> slmPolicy = stringDeduplicator.computeIfAbsent(parser.text(), Function.identity()); } } assert (startTimeMillis == -1) == (endTimeMillis == -1) : "unexpected: " + startTimeMillis + ", " + endTimeMillis + ", "; @@ -971,10 +958,8 @@ private static void parseIndices( final String indexMetaFieldName = parser.currentName(); final XContentParser.Token currentToken = parser.nextToken(); switch (indexMetaFieldName) { - case INDEX_ID: - indexId = new IndexId(indexName, parser.text()); - break; - case SNAPSHOTS: + case INDEX_ID -> indexId = new IndexId(indexName, parser.text()); + case SNAPSHOTS -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_ARRAY, currentToken, parser); XContentParser.Token currToken; while ((currToken = parser.nextToken()) != XContentParser.Token.END_ARRAY) { @@ -1003,13 +988,13 @@ private static void parseIndices( } snapshotIds.add(snapshotId); } - break; - case SHARD_GENERATIONS: + } + case SHARD_GENERATIONS -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_ARRAY, currentToken, parser); while (parser.nextToken() != XContentParser.Token.END_ARRAY) { gens.add(ShardGeneration.fromXContent(parser)); } - break; + } } } assert indexId != null; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptMetadata.java b/server/src/main/java/org/elasticsearch/script/ScriptMetadata.java index e2a0782d0cb6c..93ee39414fa7e 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptMetadata.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptMetadata.java @@ -190,17 +190,14 @@ public static ScriptMetadata fromXContent(XContentParser parser) throws IOExcept while (token != Token.END_OBJECT) { switch (token) { - case FIELD_NAME: - id = parser.currentName(); - break; - case START_OBJECT: + case FIELD_NAME -> id = parser.currentName(); + case START_OBJECT -> { if (id == null) { throw new ParsingException( parser.getTokenLocation(), "unexpected token [" + token + "], expected [, , {]" ); } - StoredScriptSource source = StoredScriptSource.fromXContent(parser, true); // as of 8.0 we drop scripts/templates with an empty source // this check should be removed for the next upgradable version after 8.0 @@ -214,11 +211,12 @@ public static ScriptMetadata fromXContent(XContentParser parser) throws IOExcept } else { scripts.put(id, source); } - id = null; - break; - default: - throw new ParsingException(parser.getTokenLocation(), "unexpected token [" + token + "], expected [, , {]"); + } + default -> throw new ParsingException( + parser.getTokenLocation(), + "unexpected token [" + token + "], expected [, , {]" + ); } token = parser.nextToken(); diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java index 867c63393c7f0..1f7ff660310ec 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java @@ -124,11 +124,8 @@ private static AggregatorFactories.Builder parseAggregators(XContentParser parse token = parser.nextToken(); if (token == XContentParser.Token.START_OBJECT) { switch (fieldName) { - case "meta": - metadata = parser.map(); - break; - case "aggregations": - case "aggs": + case "meta" -> metadata = parser.map(); + case "aggregations", "aggs" -> { if (subFactories != null) { throw new ParsingException( parser.getTokenLocation(), @@ -136,8 +133,8 @@ private static AggregatorFactories.Builder parseAggregators(XContentParser parse ); } subFactories = parseAggregators(parser, level + 1); - break; - default: + } + default -> { if (aggBuilder != null) { throw new ParsingException( parser.getTokenLocation(), @@ -150,7 +147,6 @@ private static AggregatorFactories.Builder parseAggregators(XContentParser parse + "]" ); } - try { aggBuilder = parser.namedObject(BaseAggregationBuilder.class, fieldName, aggregationName); } catch (NamedObjectNotFoundException ex) { @@ -162,6 +158,7 @@ private static AggregatorFactories.Builder parseAggregators(XContentParser parse ); throw new ParsingException(new XContentLocation(ex.getLineNumber(), ex.getColumnNumber()), message, ex); } + } } } else { throw new ParsingException( diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/InternalOrder.java b/server/src/main/java/org/elasticsearch/search/aggregations/InternalOrder.java index 343f77fbf8be5..b8ec1a6e72fa0 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/InternalOrder.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/InternalOrder.java @@ -582,14 +582,12 @@ public static BucketOrder parseOrderParam(XContentParser parser) throws IOExcept ); return orderAsc ? KEY_ASC : KEY_DESC; } - switch (orderKey) { - case "_key": - return orderAsc ? KEY_ASC : KEY_DESC; - case "_count": - return orderAsc ? COUNT_ASC : COUNT_DESC; - default: // assume all other orders are sorting on a sub-aggregation. Validation occurs later. - return aggregation(orderKey, orderAsc); - } + return switch (orderKey) { + case "_key" -> orderAsc ? KEY_ASC : KEY_DESC; + case "_count" -> orderAsc ? COUNT_ASC : COUNT_DESC; + default -> // assume all other orders are sorting on a sub-aggregation. Validation occurs later. + aggregation(orderKey, orderAsc); + }; } } } diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesSourceParserHelper.java b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesSourceParserHelper.java index b362f9421f35b..44c629a2048af 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesSourceParserHelper.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesSourceParserHelper.java @@ -75,18 +75,13 @@ public static void writeTo(CompositeValuesSourceBuilder builder, StreamOutput public static CompositeValuesSourceBuilder readFrom(StreamInput in) throws IOException { int code = in.readByte(); - switch (code) { - case 0: - return new TermsValuesSourceBuilder(in); - case 1: - return new DateHistogramValuesSourceBuilder(in); - case 2: - return new HistogramValuesSourceBuilder(in); - case 3: - return new GeoTileGridValuesSourceBuilder(in); - default: - throw new IOException("Invalid code " + code); - } + return switch (code) { + case 0 -> new TermsValuesSourceBuilder(in); + case 1 -> new DateHistogramValuesSourceBuilder(in); + case 2 -> new HistogramValuesSourceBuilder(in); + case 3 -> new GeoTileGridValuesSourceBuilder(in); + default -> throw new IOException("Invalid code " + code); + }; } public static CompositeValuesSourceBuilder fromXContent(XContentParser parser) throws IOException { @@ -102,23 +97,13 @@ public static CompositeValuesSourceBuilder fromXContent(XContentParser parser String type = parser.currentName(); token = parser.nextToken(); ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); - final CompositeValuesSourceBuilder builder; - switch (type) { - case TermsValuesSourceBuilder.TYPE: - builder = TermsValuesSourceBuilder.parse(name, parser); - break; - case DateHistogramValuesSourceBuilder.TYPE: - builder = DateHistogramValuesSourceBuilder.PARSER.parse(parser, name); - break; - case HistogramValuesSourceBuilder.TYPE: - builder = HistogramValuesSourceBuilder.parse(name, parser); - break; - case GeoTileGridValuesSourceBuilder.TYPE: - builder = GeoTileGridValuesSourceBuilder.parse(name, parser); - break; - default: - throw new ParsingException(parser.getTokenLocation(), "invalid source type: " + type); - } + final CompositeValuesSourceBuilder builder = switch (type) { + case TermsValuesSourceBuilder.TYPE -> TermsValuesSourceBuilder.parse(name, parser); + case DateHistogramValuesSourceBuilder.TYPE -> DateHistogramValuesSourceBuilder.PARSER.parse(parser, name); + case HistogramValuesSourceBuilder.TYPE -> HistogramValuesSourceBuilder.parse(name, parser); + case GeoTileGridValuesSourceBuilder.TYPE -> GeoTileGridValuesSourceBuilder.parse(name, parser); + default -> throw new ParsingException(parser.getTokenLocation(), "invalid source type: " + type); + }; parser.nextToken(); parser.nextToken(); return builder; diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/RareTermsAggregatorFactory.java b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/RareTermsAggregatorFactory.java index e238239dd5b5e..77ce7dd4a4c4b 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/RareTermsAggregatorFactory.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/RareTermsAggregatorFactory.java @@ -248,12 +248,10 @@ boolean needsGlobalOrdinals() { }; public static ExecutionMode fromString(String value, final DeprecationLogger deprecationLogger) { - switch (value) { - case "map": - return MAP; - default: - throw new IllegalArgumentException("Unknown `execution_hint`: [" + value + "], expected any of [map]"); - } + return switch (value) { + case "map" -> MAP; + default -> throw new IllegalArgumentException("Unknown `execution_hint`: [" + value + "], expected any of [map]"); + }; } private final ParseField parseField; diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java index be652f48d174a..9ca76c0338e56 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java @@ -527,14 +527,13 @@ Aggregator create( }; public static ExecutionMode fromString(String value) { - switch (value) { - case "global_ordinals": - return GLOBAL_ORDINALS; - case "map": - return MAP; - default: - throw new IllegalArgumentException("Unknown `execution_hint`: [" + value + "], expected any of [map, global_ordinals]"); - } + return switch (value) { + case "global_ordinals" -> GLOBAL_ORDINALS; + case "map" -> MAP; + default -> throw new IllegalArgumentException( + "Unknown `execution_hint`: [" + value + "], expected any of [map, global_ordinals]" + ); + }; } private final ParseField parseField; diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/AbstractHyperLogLog.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/AbstractHyperLogLog.java index 1e125f48f3831..371d8c1413d8d 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/AbstractHyperLogLog.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/AbstractHyperLogLog.java @@ -714,18 +714,11 @@ public abstract class AbstractHyperLogLog extends AbstractCardinalityAlgorithm { public AbstractHyperLogLog(int precision) { super(precision); m = 1 << p; - final double alpha; - switch (p) { - case 4: - alpha = 0.673; - break; - case 5: - alpha = 0.697; - break; - default: - alpha = 0.7213 / (1 + 1.079 / m); - break; - } + final double alpha = switch (p) { + case 4 -> 0.673; + case 5 -> 0.697; + default -> 0.7213 / (1 + 1.079 / m); + }; alphaMM = alpha * m * m; } diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ExtendedStatsAggregator.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ExtendedStatsAggregator.java index 6c6437a1ba9a3..213edc138c396 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ExtendedStatsAggregator.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ExtendedStatsAggregator.java @@ -149,71 +149,43 @@ public boolean hasMetric(String name) { @Override public double metric(String name, long owningBucketOrd) { if (valuesSource == null || owningBucketOrd >= counts.size()) { - switch (InternalExtendedStats.Metrics.resolve(name)) { - case count: - return 0; - case sum: - return 0; - case min: - return Double.POSITIVE_INFINITY; - case max: - return Double.NEGATIVE_INFINITY; - case avg: - return Double.NaN; - case sum_of_squares: - return 0; - case variance: - return Double.NaN; - case variance_population: - return Double.NaN; - case variance_sampling: - return Double.NaN; - case std_deviation: - return Double.NaN; - case std_deviation_population: - return Double.NaN; - case std_deviation_sampling: - return Double.NaN; - case std_upper: - return Double.NaN; - case std_lower: - return Double.NaN; - default: - throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); - } - } - switch (InternalExtendedStats.Metrics.resolve(name)) { - case count: - return counts.get(owningBucketOrd); - case sum: - return sums.get(owningBucketOrd); - case min: - return mins.get(owningBucketOrd); - case max: - return maxes.get(owningBucketOrd); - case avg: - return sums.get(owningBucketOrd) / counts.get(owningBucketOrd); - case sum_of_squares: - return sumOfSqrs.get(owningBucketOrd); - case variance: - return variance(owningBucketOrd); - case variance_population: - return variancePopulation(owningBucketOrd); - case variance_sampling: - return varianceSampling(owningBucketOrd); - case std_deviation: - return Math.sqrt(variance(owningBucketOrd)); - case std_deviation_population: - return Math.sqrt(variance(owningBucketOrd)); - case std_deviation_sampling: - return Math.sqrt(varianceSampling(owningBucketOrd)); - case std_upper: - return (sums.get(owningBucketOrd) / counts.get(owningBucketOrd)) + (Math.sqrt(variance(owningBucketOrd)) * this.sigma); - case std_lower: - return (sums.get(owningBucketOrd) / counts.get(owningBucketOrd)) - (Math.sqrt(variance(owningBucketOrd)) * this.sigma); - default: - throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); + return switch (InternalExtendedStats.Metrics.resolve(name)) { + case count -> 0; + case sum -> 0; + case min -> Double.POSITIVE_INFINITY; + case max -> Double.NEGATIVE_INFINITY; + case avg -> Double.NaN; + case sum_of_squares -> 0; + case variance -> Double.NaN; + case variance_population -> Double.NaN; + case variance_sampling -> Double.NaN; + case std_deviation -> Double.NaN; + case std_deviation_population -> Double.NaN; + case std_deviation_sampling -> Double.NaN; + case std_upper -> Double.NaN; + case std_lower -> Double.NaN; + default -> throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); + }; } + return switch (InternalExtendedStats.Metrics.resolve(name)) { + case count -> counts.get(owningBucketOrd); + case sum -> sums.get(owningBucketOrd); + case min -> mins.get(owningBucketOrd); + case max -> maxes.get(owningBucketOrd); + case avg -> sums.get(owningBucketOrd) / counts.get(owningBucketOrd); + case sum_of_squares -> sumOfSqrs.get(owningBucketOrd); + case variance -> variance(owningBucketOrd); + case variance_population -> variancePopulation(owningBucketOrd); + case variance_sampling -> varianceSampling(owningBucketOrd); + case std_deviation -> Math.sqrt(variance(owningBucketOrd)); + case std_deviation_population -> Math.sqrt(variance(owningBucketOrd)); + case std_deviation_sampling -> Math.sqrt(varianceSampling(owningBucketOrd)); + case std_upper -> (sums.get(owningBucketOrd) / counts.get(owningBucketOrd)) + (Math.sqrt(variance(owningBucketOrd)) + * this.sigma); + case std_lower -> (sums.get(owningBucketOrd) / counts.get(owningBucketOrd)) - (Math.sqrt(variance(owningBucketOrd)) + * this.sigma); + default -> throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); + }; } private double variance(long owningBucketOrd) { diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalExtendedStats.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalExtendedStats.java index c60ec7f87e461..2f91d28e0303c 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalExtendedStats.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalExtendedStats.java @@ -184,20 +184,12 @@ public double getStdDeviationSampling() { @Override public double getStdDeviationBound(Bounds bound) { - switch (bound) { - case UPPER: - case UPPER_POPULATION: - return getAvg() + (getStdDeviationPopulation() * sigma); - case UPPER_SAMPLING: - return getAvg() + (getStdDeviationSampling() * sigma); - case LOWER: - case LOWER_POPULATION: - return getAvg() - (getStdDeviationPopulation() * sigma); - case LOWER_SAMPLING: - return getAvg() - (getStdDeviationSampling() * sigma); - default: - throw new IllegalArgumentException("Unknown bounds type " + bound); - } + return switch (bound) { + case UPPER, UPPER_POPULATION -> getAvg() + (getStdDeviationPopulation() * sigma); + case UPPER_SAMPLING -> getAvg() + (getStdDeviationSampling() * sigma); + case LOWER, LOWER_POPULATION -> getAvg() - (getStdDeviationPopulation() * sigma); + case LOWER_SAMPLING -> getAvg() - (getStdDeviationSampling() * sigma); + }; } @Override @@ -237,22 +229,14 @@ public String getStdDeviationSamplingAsString() { @Override public String getStdDeviationBoundAsString(Bounds bound) { - switch (bound) { - case UPPER: - return valueAsString(Metrics.std_upper.name()); - case LOWER: - return valueAsString(Metrics.std_lower.name()); - case UPPER_POPULATION: - return valueAsString(Metrics.std_upper_population.name()); - case LOWER_POPULATION: - return valueAsString(Metrics.std_lower_population.name()); - case UPPER_SAMPLING: - return valueAsString(Metrics.std_upper_sampling.name()); - case LOWER_SAMPLING: - return valueAsString(Metrics.std_lower_sampling.name()); - default: - throw new IllegalArgumentException("Unknown bounds type " + bound); - } + return switch (bound) { + case UPPER -> valueAsString(Metrics.std_upper.name()); + case LOWER -> valueAsString(Metrics.std_lower.name()); + case UPPER_POPULATION -> valueAsString(Metrics.std_upper_population.name()); + case LOWER_POPULATION -> valueAsString(Metrics.std_lower_population.name()); + case UPPER_SAMPLING -> valueAsString(Metrics.std_upper_sampling.name()); + case LOWER_SAMPLING -> valueAsString(Metrics.std_lower_sampling.name()); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoBounds.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoBounds.java index c19de43b4cc88..7b58226925964 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoBounds.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoBounds.java @@ -126,41 +126,28 @@ public Object getProperty(List path) { } else if (path.size() == 1) { GeoBoundingBox geoBoundingBox = resolveGeoBoundingBox(); String bBoxSide = path.get(0); - switch (bBoxSide) { - case "top": - return geoBoundingBox.top(); - case "left": - return geoBoundingBox.left(); - case "bottom": - return geoBoundingBox.bottom(); - case "right": - return geoBoundingBox.right(); - default: - throw new IllegalArgumentException("Found unknown path element [" + bBoxSide + "] in [" + getName() + "]"); - } + return switch (bBoxSide) { + case "top" -> geoBoundingBox.top(); + case "left" -> geoBoundingBox.left(); + case "bottom" -> geoBoundingBox.bottom(); + case "right" -> geoBoundingBox.right(); + default -> throw new IllegalArgumentException("Found unknown path element [" + bBoxSide + "] in [" + getName() + "]"); + }; } else if (path.size() == 2) { GeoBoundingBox geoBoundingBox = resolveGeoBoundingBox(); GeoPoint cornerPoint = null; String cornerString = path.get(0); - switch (cornerString) { - case "top_left": - cornerPoint = geoBoundingBox.topLeft(); - break; - case "bottom_right": - cornerPoint = geoBoundingBox.bottomRight(); - break; - default: - throw new IllegalArgumentException("Found unknown path element [" + cornerString + "] in [" + getName() + "]"); - } + cornerPoint = switch (cornerString) { + case "top_left" -> geoBoundingBox.topLeft(); + case "bottom_right" -> geoBoundingBox.bottomRight(); + default -> throw new IllegalArgumentException("Found unknown path element [" + cornerString + "] in [" + getName() + "]"); + }; String latLonString = path.get(1); - switch (latLonString) { - case "lat": - return cornerPoint.lat(); - case "lon": - return cornerPoint.lon(); - default: - throw new IllegalArgumentException("Found unknown path element [" + latLonString + "] in [" + getName() + "]"); - } + return switch (latLonString) { + case "lat" -> cornerPoint.lat(); + case "lon" -> cornerPoint.lon(); + default -> throw new IllegalArgumentException("Found unknown path element [" + latLonString + "] in [" + getName() + "]"); + }; } else { throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path); } diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoCentroid.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoCentroid.java index 25f9ee191df04..422d5e9417910 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoCentroid.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalGeoCentroid.java @@ -134,18 +134,13 @@ public Object getProperty(List path) { return this; } else if (path.size() == 1) { String coordinate = path.get(0); - switch (coordinate) { - case "value": - return centroid; - case "lat": - return centroid.lat(); - case "lon": - return centroid.lon(); - case "count": - return count; - default: - throw new IllegalArgumentException("Found unknown path element [" + coordinate + "] in [" + getName() + "]"); - } + return switch (coordinate) { + case "value" -> centroid; + case "lat" -> centroid.lat(); + case "lon" -> centroid.lon(); + case "count" -> count; + default -> throw new IllegalArgumentException("Found unknown path element [" + coordinate + "] in [" + getName() + "]"); + }; } else { throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path); } diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalStats.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalStats.java index aecb85250e8d9..95692c2ac5c00 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalStats.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalStats.java @@ -139,20 +139,13 @@ public String getSumAsString() { @Override public double value(String name) { Metrics metrics = Metrics.valueOf(name); - switch (metrics) { - case min: - return this.min; - case max: - return this.max; - case avg: - return this.getAvg(); - case count: - return this.count; - case sum: - return this.sum; - default: - throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); - } + return switch (metrics) { + case min -> this.min; + case max -> this.max; + case avg -> this.getAvg(); + case count -> this.count; + case sum -> this.sum; + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedExtendedStats.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedExtendedStats.java index 9bb1ecf2d8202..183d496d776da 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedExtendedStats.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedExtendedStats.java @@ -94,22 +94,14 @@ private void setStdDeviationBounds(List bounds) { @Override public double getStdDeviationBound(Bounds bound) { - switch (bound) { - case UPPER: - return stdDeviationBoundUpper; - case UPPER_POPULATION: - return stdDeviationBoundUpperPopulation; - case UPPER_SAMPLING: - return stdDeviationBoundUpperSampling; - case LOWER: - return stdDeviationBoundLower; - case LOWER_POPULATION: - return stdDeviationBoundLowerPopulation; - case LOWER_SAMPLING: - return stdDeviationBoundLowerSampling; - default: - throw new IllegalArgumentException("Unknown bounds type " + bound); - } + return switch (bound) { + case UPPER -> stdDeviationBoundUpper; + case UPPER_POPULATION -> stdDeviationBoundUpperPopulation; + case UPPER_SAMPLING -> stdDeviationBoundUpperSampling; + case LOWER -> stdDeviationBoundLower; + case LOWER_POPULATION -> stdDeviationBoundLowerPopulation; + case LOWER_SAMPLING -> stdDeviationBoundLowerSampling; + }; } private void setStdDeviationBoundsAsString(List boundsAsString) { @@ -146,40 +138,32 @@ public String getStdDeviationSamplingAsString() { @Override public String getStdDeviationBoundAsString(Bounds bound) { - switch (bound) { - case UPPER: - return valueAsString.getOrDefault( - Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_upper", - Double.toString(stdDeviationBoundUpper) - ); - case UPPER_POPULATION: - return valueAsString.getOrDefault( - Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_upper_population", - Double.toString(stdDeviationBoundUpperPopulation) - ); - case UPPER_SAMPLING: - return valueAsString.getOrDefault( - Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_upper_sampling", - Double.toString(stdDeviationBoundUpperSampling) - ); - case LOWER: - return valueAsString.getOrDefault( - Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_lower", - Double.toString(stdDeviationBoundLower) - ); - case LOWER_POPULATION: - return valueAsString.getOrDefault( - Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_lower_population", - Double.toString(stdDeviationBoundLowerPopulation) - ); - case LOWER_SAMPLING: - return valueAsString.getOrDefault( - Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_lower_sampling", - Double.toString(stdDeviationBoundLowerSampling) - ); - default: - throw new IllegalArgumentException("Unknown bounds type " + bound); - } + return switch (bound) { + case UPPER -> valueAsString.getOrDefault( + Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_upper", + Double.toString(stdDeviationBoundUpper) + ); + case UPPER_POPULATION -> valueAsString.getOrDefault( + Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_upper_population", + Double.toString(stdDeviationBoundUpperPopulation) + ); + case UPPER_SAMPLING -> valueAsString.getOrDefault( + Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_upper_sampling", + Double.toString(stdDeviationBoundUpperSampling) + ); + case LOWER -> valueAsString.getOrDefault( + Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_lower", + Double.toString(stdDeviationBoundLower) + ); + case LOWER_POPULATION -> valueAsString.getOrDefault( + Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_lower_population", + Double.toString(stdDeviationBoundLowerPopulation) + ); + case LOWER_SAMPLING -> valueAsString.getOrDefault( + Fields.STD_DEVIATION_BOUNDS_AS_STRING + "_lower_sampling", + Double.toString(stdDeviationBoundLowerSampling) + ); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedStats.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedStats.java index 52de1ea23156a..c6621844c8b88 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedStats.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedStats.java @@ -81,20 +81,13 @@ public String getSumAsString() { @Override public double value(String name) { Metrics metrics = Metrics.valueOf(name); - switch (metrics) { - case min: - return min; - case max: - return max; - case avg: - return avg; - case count: - return count; - case sum: - return sum; - default: - throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); - } + return switch (metrics) { + case min -> min; + case max -> max; + case avg -> avg; + case count -> count; + case sum -> sum; + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/StatsAggregator.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/StatsAggregator.java index c6aa5521d7693..e30c08957122b 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/StatsAggregator.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/StatsAggregator.java @@ -126,35 +126,21 @@ public boolean hasMetric(String name) { @Override public double metric(String name, long owningBucketOrd) { if (valuesSource == null || owningBucketOrd >= counts.size()) { - switch (InternalStats.Metrics.resolve(name)) { - case count: - return 0; - case sum: - return 0; - case min: - return Double.POSITIVE_INFINITY; - case max: - return Double.NEGATIVE_INFINITY; - case avg: - return Double.NaN; - default: - throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); - } - } - switch (InternalStats.Metrics.resolve(name)) { - case count: - return counts.get(owningBucketOrd); - case sum: - return sums.get(owningBucketOrd); - case min: - return mins.get(owningBucketOrd); - case max: - return maxes.get(owningBucketOrd); - case avg: - return sums.get(owningBucketOrd) / counts.get(owningBucketOrd); - default: - throw new IllegalArgumentException("Unknown value [" + name + "] in common stats aggregation"); + return switch (InternalStats.Metrics.resolve(name)) { + case count -> 0; + case sum -> 0; + case min -> Double.POSITIVE_INFINITY; + case max -> Double.NEGATIVE_INFINITY; + case avg -> Double.NaN; + }; } + return switch (InternalStats.Metrics.resolve(name)) { + case count -> counts.get(owningBucketOrd); + case sum -> sums.get(owningBucketOrd); + case min -> mins.get(owningBucketOrd); + case max -> maxes.get(owningBucketOrd); + case avg -> sums.get(owningBucketOrd) / counts.get(owningBucketOrd); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/support/ValueType.java b/server/src/main/java/org/elasticsearch/search/aggregations/support/ValueType.java index 3a598494b58cf..2106976252581 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/support/ValueType.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/support/ValueType.java @@ -106,29 +106,17 @@ public DocValueFormat defaultFormat() { } public static ValueType lenientParse(String type) { - switch (type) { - case "string": - return STRING; - case "double": - case "float": - return DOUBLE; - case "number": - case "numeric": - case "long": - case "integer": - case "short": - case "byte": - return LONG; - case "date": - return DATE; - case "ip": - return IP; - case "boolean": - return BOOLEAN; - default: + return switch (type) { + case "string" -> STRING; + case "double", "float" -> DOUBLE; + case "number", "numeric", "long", "integer", "short", "byte" -> LONG; + case "date" -> DATE; + case "ip" -> IP; + case "boolean" -> BOOLEAN; + default -> // TODO: do not be lenient here - return null; - } + null; + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java index 536909140271c..1c451bb045545 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java @@ -278,24 +278,26 @@ private static BoundaryScanner getBoundaryScanner(Field field) { ? fieldOptions.boundaryScannerType() : HighlightBuilder.BoundaryScannerType.CHARS; switch (type) { - case SENTENCE: + case SENTENCE -> { if (boundaryScannerLocale != null) { return new BreakIteratorBoundaryScanner(BreakIterator.getSentenceInstance(boundaryScannerLocale)); } return DEFAULT_SENTENCE_BOUNDARY_SCANNER; - case WORD: + } + case WORD -> { if (boundaryScannerLocale != null) { return new BreakIteratorBoundaryScanner(BreakIterator.getWordInstance(boundaryScannerLocale)); } return DEFAULT_WORD_BOUNDARY_SCANNER; - case CHARS: + } + case CHARS -> { if (fieldOptions.boundaryMaxScan() != SimpleBoundaryScanner.DEFAULT_MAX_SCAN || fieldOptions.boundaryChars() != SimpleBoundaryScanner.DEFAULT_BOUNDARY_CHARS) { return new SimpleBoundaryScanner(fieldOptions.boundaryMaxScan(), fieldOptions.boundaryChars()); } return DEFAULT_SIMPLE_BOUNDARY_SCANNER; - default: - throw new IllegalArgumentException("Invalid boundary scanner type: " + type.toString()); + } + default -> throw new IllegalArgumentException("Invalid boundary scanner type: " + type.toString()); } } diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightBuilder.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightBuilder.java index 9d391bf6ee4ec..30527069006bd 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightBuilder.java @@ -207,16 +207,15 @@ public List fields() { */ public HighlightBuilder tagsSchema(String schemaName) { switch (schemaName) { - case "default": + case "default" -> { preTags(DEFAULT_PRE_TAGS); postTags(DEFAULT_POST_TAGS); - break; - case "styled": + } + case "styled" -> { preTags(DEFAULT_STYLED_PRE_TAG); postTags(DEFAULT_STYLED_POST_TAGS); - break; - default: - throw new IllegalArgumentException("Unknown tag schema [" + schemaName + "]"); + } + default -> throw new IllegalArgumentException("Unknown tag schema [" + schemaName + "]"); } return this; } diff --git a/server/src/main/java/org/elasticsearch/search/runtime/GeoPointScriptFieldGeoShapeQuery.java b/server/src/main/java/org/elasticsearch/search/runtime/GeoPointScriptFieldGeoShapeQuery.java index 0faa847d4de0e..68b016c57d348 100644 --- a/server/src/main/java/org/elasticsearch/search/runtime/GeoPointScriptFieldGeoShapeQuery.java +++ b/server/src/main/java/org/elasticsearch/search/runtime/GeoPointScriptFieldGeoShapeQuery.java @@ -71,7 +71,7 @@ private interface SpatialPredicate { private static SpatialPredicate getPredicate(ShapeRelation relation, LatLonGeometry... geometries) { switch (relation) { - case INTERSECTS: { + case INTERSECTS -> { final GeoEncodingUtils.Component2DPredicate predicate = GeoEncodingUtils.createComponentPredicate( LatLonGeometry.create(geometries) ); @@ -87,7 +87,7 @@ private static SpatialPredicate getPredicate(ShapeRelation relation, LatLonGeome return false; }; } - case DISJOINT: { + case DISJOINT -> { final GeoEncodingUtils.Component2DPredicate predicate = GeoEncodingUtils.createComponentPredicate( LatLonGeometry.create(geometries) ); @@ -104,7 +104,7 @@ private static SpatialPredicate getPredicate(ShapeRelation relation, LatLonGeome return count > 0; }; } - case WITHIN: { + case WITHIN -> { final GeoEncodingUtils.Component2DPredicate predicate = GeoEncodingUtils.createComponentPredicate( LatLonGeometry.create(geometries) ); @@ -121,7 +121,7 @@ private static SpatialPredicate getPredicate(ShapeRelation relation, LatLonGeome return count > 0; }; } - case CONTAINS: { + case CONTAINS -> { final Component2D[] component2DS = new Component2D[geometries.length]; for (int i = 0; i < geometries.length; i++) { component2DS[i] = LatLonGeometry.create(geometries[i]); @@ -144,8 +144,7 @@ private static SpatialPredicate getPredicate(ShapeRelation relation, LatLonGeome return answer == Component2D.WithinRelation.CANDIDATE; }; } - default: - throw new IllegalArgumentException("Unknown spatial relationship [" + relation.getRelationName() + "]"); + default -> throw new IllegalArgumentException("Unknown spatial relationship [" + relation.getRelationName() + "]"); } } } diff --git a/server/src/main/java/org/elasticsearch/search/searchafter/SearchAfterBuilder.java b/server/src/main/java/org/elasticsearch/search/searchafter/SearchAfterBuilder.java index 39f8dff072623..2960ed0e21ef5 100644 --- a/server/src/main/java/org/elasticsearch/search/searchafter/SearchAfterBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/searchafter/SearchAfterBuilder.java @@ -234,30 +234,14 @@ public static SearchAfterBuilder fromXContent(XContentParser parser) throws IOEx while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.VALUE_NUMBER) { switch (parser.numberType()) { - case INT: - values.add(parser.intValue()); - break; - - case LONG: - values.add(parser.longValue()); - break; - - case DOUBLE: - values.add(parser.doubleValue()); - break; - - case FLOAT: - values.add(parser.floatValue()); - break; - - case BIG_INTEGER: - values.add(parser.text()); - break; - - default: - throw new IllegalArgumentException( - "[search_after] does not accept numbers of type [" + parser.numberType() + "], got " + parser.text() - ); + case INT -> values.add(parser.intValue()); + case LONG -> values.add(parser.longValue()); + case DOUBLE -> values.add(parser.doubleValue()); + case FLOAT -> values.add(parser.floatValue()); + case BIG_INTEGER -> values.add(parser.text()); + default -> throw new IllegalArgumentException( + "[search_after] does not accept numbers of type [" + parser.numberType() + "], got " + parser.text() + ); } } else if (token == XContentParser.Token.VALUE_STRING) { values.add(parser.text()); diff --git a/server/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java b/server/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java index 42f7ec8050492..d4706cd7587e2 100644 --- a/server/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/sort/FieldSortBuilder.java @@ -336,21 +336,15 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws } private static NumericType resolveNumericType(String value) { - switch (value) { - case "long": - return NumericType.LONG; - case "double": - return NumericType.DOUBLE; - case "date": - return NumericType.DATE; - case "date_nanos": - return NumericType.DATE_NANOSECONDS; - - default: - throw new IllegalArgumentException( - "invalid value for [numeric_type], " + "must be [long, double, date, date_nanos], got " + value - ); - } + return switch (value) { + case "long" -> NumericType.LONG; + case "double" -> NumericType.DOUBLE; + case "date" -> NumericType.DATE; + case "date_nanos" -> NumericType.DATE_NANOSECONDS; + default -> throw new IllegalArgumentException( + "invalid value for [numeric_type], " + "must be [long, double, date, date_nanos], got " + value + ); + }; } @Override @@ -616,18 +610,13 @@ private static MinAndMax extractNumericMinAndMax( if (fieldType instanceof NumberFieldType numberFieldType) { Number minPoint = numberFieldType.parsePoint(PointValues.getMinPackedValue(reader, fieldName)); Number maxPoint = numberFieldType.parsePoint(PointValues.getMaxPackedValue(reader, fieldName)); - switch (IndexSortConfig.getSortFieldType(sortField)) { - case LONG: - return new MinAndMax<>(minPoint.longValue(), maxPoint.longValue()); - case INT: - return new MinAndMax<>(minPoint.intValue(), maxPoint.intValue()); - case DOUBLE: - return new MinAndMax<>(minPoint.doubleValue(), maxPoint.doubleValue()); - case FLOAT: - return new MinAndMax<>(minPoint.floatValue(), maxPoint.floatValue()); - default: - return null; - } + return switch (IndexSortConfig.getSortFieldType(sortField)) { + case LONG -> new MinAndMax<>(minPoint.longValue(), maxPoint.longValue()); + case INT -> new MinAndMax<>(minPoint.intValue(), maxPoint.intValue()); + case DOUBLE -> new MinAndMax<>(minPoint.doubleValue(), maxPoint.doubleValue()); + case FLOAT -> new MinAndMax<>(minPoint.floatValue(), maxPoint.floatValue()); + default -> null; + }; } else if (fieldType instanceof DateFieldType dateFieldType) { Function dateConverter = createDateConverter(sortBuilder, dateFieldType); Long min = dateConverter.apply(PointValues.getMinPackedValue(reader, fieldName)); diff --git a/server/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java b/server/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java index 18e39dedf170a..9eed79459e5f2 100644 --- a/server/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/sort/ScriptSortBuilder.java @@ -275,7 +275,7 @@ private IndexFieldData.XFieldComparatorSource fieldComparatorSource(SearchExecut SearchLookup searchLookup = context.lookup(); switch (type) { - case STRING: + case STRING -> { final StringSortScript.Factory factory = context.compile(script, StringSortScript.CONTEXT); final StringSortScript.LeafFactory searchScript = factory.newFactory(script.getParams()); return new BytesRefFieldComparatorSource(null, null, valueMode, nested) { @@ -323,7 +323,8 @@ public BucketedSort newBucketedSort( ); } }; - case NUMBER: + } + case NUMBER -> { final NumberSortScript.Factory numberSortFactory = context.compile(script, NumberSortScript.CONTEXT); // searchLookup is unnecessary here, as it's just used for expressions final NumberSortScript.LeafFactory numberSortScript = numberSortFactory.newFactory(script.getParams(), searchLookup); @@ -353,8 +354,8 @@ protected void setScorer(Scorable scorer) { leafScript.setScorer(scorer); } }; - default: - throw new QueryShardException(context, "custom script sort type [" + type + "] not supported"); + } + default -> throw new QueryShardException(context, "custom script sort type [" + type + "] not supported"); } } @@ -404,14 +405,11 @@ static ScriptSortType readFromStream(final StreamInput in) throws IOException { public static ScriptSortType fromString(final String str) { Objects.requireNonNull(str, "input string is null"); - switch (str.toLowerCase(Locale.ROOT)) { - case ("string"): - return ScriptSortType.STRING; - case ("number"): - return ScriptSortType.NUMBER; - default: - throw new IllegalArgumentException("Unknown ScriptSortType [" + str + "]"); - } + return switch (str.toLowerCase(Locale.ROOT)) { + case ("string") -> ScriptSortType.STRING; + case ("number") -> ScriptSortType.NUMBER; + default -> throw new IllegalArgumentException("Unknown ScriptSortType [" + str + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/sort/SortMode.java b/server/src/main/java/org/elasticsearch/search/sort/SortMode.java index 79c0320c1530e..681f911eb3d6a 100644 --- a/server/src/main/java/org/elasticsearch/search/sort/SortMode.java +++ b/server/src/main/java/org/elasticsearch/search/sort/SortMode.java @@ -50,20 +50,14 @@ public static SortMode readFromStream(StreamInput in) throws IOException { public static SortMode fromString(final String str) { Objects.requireNonNull(str, "input string is null"); - switch (str.toLowerCase(Locale.ROOT)) { - case ("min"): - return MIN; - case ("max"): - return MAX; - case ("sum"): - return SUM; - case ("avg"): - return AVG; - case ("median"): - return MEDIAN; - default: - throw new IllegalArgumentException("Unknown SortMode [" + str + "]"); - } + return switch (str.toLowerCase(Locale.ROOT)) { + case "min" -> MIN; + case "max" -> MAX; + case "sum" -> SUM; + case "avg" -> AVG; + case "median" -> MEDIAN; + default -> throw new IllegalArgumentException("Unknown SortMode [" + str + "]"); + }; } @Override diff --git a/server/src/main/java/org/elasticsearch/search/suggest/DirectSpellcheckerSettings.java b/server/src/main/java/org/elasticsearch/search/suggest/DirectSpellcheckerSettings.java index 4f5a427c6bcce..80beb5d2ec7ca 100644 --- a/server/src/main/java/org/elasticsearch/search/suggest/DirectSpellcheckerSettings.java +++ b/server/src/main/java/org/elasticsearch/search/suggest/DirectSpellcheckerSettings.java @@ -130,17 +130,10 @@ public DirectSpellChecker createDirectSpellChecker() { DirectSpellChecker directSpellChecker = new DirectSpellChecker(); directSpellChecker.setAccuracy(accuracy()); - Comparator comparator; - switch (sort()) { - case SCORE: - comparator = SCORE_COMPARATOR; - break; - case FREQUENCY: - comparator = LUCENE_FREQUENCY; - break; - default: - throw new IllegalArgumentException("Illegal suggest sort: " + sort()); - } + Comparator comparator = switch (sort()) { + case SCORE -> SCORE_COMPARATOR; + case FREQUENCY -> LUCENE_FREQUENCY; + }; directSpellChecker.setComparator(comparator); directSpellChecker.setDistance(stringDistance()); directSpellChecker.setMaxEdits(maxEdits()); diff --git a/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMappings.java b/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMappings.java index 54868b2bfd7e0..6652b09ebabd6 100644 --- a/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMappings.java +++ b/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMappings.java @@ -234,17 +234,10 @@ public static ContextMappings load(Object configuration) throws ElasticsearchPar private static ContextMapping load(Map contextConfig) { String name = extractRequiredValue(contextConfig, FIELD_NAME); String type = extractRequiredValue(contextConfig, FIELD_TYPE); - final ContextMapping contextMapping; - switch (Type.fromString(type)) { - case CATEGORY: - contextMapping = CategoryContextMapping.load(name, contextConfig); - break; - case GEO: - contextMapping = GeoContextMapping.load(name, contextConfig); - break; - default: - throw new ElasticsearchParseException("unknown context type[" + type + "]"); - } + final ContextMapping contextMapping = switch (Type.fromString(type)) { + case CATEGORY -> CategoryContextMapping.load(name, contextConfig); + case GEO -> GeoContextMapping.load(name, contextConfig); + }; MappingParser.checkNoRemainingFields(name, contextConfig); return contextMapping; } diff --git a/server/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestion.java b/server/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestion.java index 849ac33bfdb1e..0cb7ddac471b2 100644 --- a/server/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestion.java +++ b/server/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestion.java @@ -7,7 +7,6 @@ */ package org.elasticsearch.search.suggest.term; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.text.Text; @@ -96,14 +95,10 @@ public SortBy getSort() { @Override protected Comparator