Skip to content

Commit 0699c93

Browse files
authored
Use Java 14 switch expressions (#82178)
JEP 361[https://openjdk.java.net/jeps/361] added support for switch expressions which can be much more terse and less error-prone than switch statements. Another useful feature of switch expressions is exhaustiveness: we can make sure that an enum switch expression covers all the cases at compile time.
1 parent 35a79bc commit 0699c93

File tree

720 files changed

+7815
-13308
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

720 files changed

+7815
-13308
lines changed

benchmarks/src/main/java/org/elasticsearch/benchmark/indices/common/RoundingBenchmark.java

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -89,16 +89,11 @@ public void buildDates() {
8989
roundingBuilder = Rounding.builder(TimeValue.parseTimeValue(interval, "interval"));
9090
}
9191
Rounding rounding = roundingBuilder.timeZone(ZoneId.of(zone)).build();
92-
switch (rounder) {
93-
case "java time":
94-
rounderBuilder = rounding::prepareJavaTime;
95-
break;
96-
case "es":
97-
rounderBuilder = () -> rounding.prepare(min, max);
98-
break;
99-
default:
100-
throw new IllegalArgumentException("Expectd rounder to be [java time] or [es]");
101-
}
92+
rounderBuilder = switch (rounder) {
93+
case "java time" -> rounding::prepareJavaTime;
94+
case "es" -> () -> rounding.prepare(min, max);
95+
default -> throw new IllegalArgumentException("Expected rounder to be [java time] or [es]");
96+
};
10297
}
10398

10499
@Benchmark

benchmarks/src/main/java/org/elasticsearch/benchmark/script/ScriptScoreBenchmark.java

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -101,28 +101,19 @@ public class ScriptScoreBenchmark {
101101

102102
@Setup
103103
public void setupScript() {
104-
switch (script) {
105-
case "expression":
106-
factory = scriptModule.engines.get("expression").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
107-
break;
108-
case "metal":
109-
factory = bareMetalScript();
110-
break;
111-
case "painless_cast":
112-
factory = scriptModule.engines.get("painless")
113-
.compile(
114-
"test",
115-
"((org.elasticsearch.index.fielddata.ScriptDocValues.Longs)doc['n']).value",
116-
ScoreScript.CONTEXT,
117-
Map.of()
118-
);
119-
break;
120-
case "painless_def":
121-
factory = scriptModule.engines.get("painless").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
122-
break;
123-
default:
124-
throw new IllegalArgumentException("Don't know how to implement script [" + script + "]");
125-
}
104+
factory = switch (script) {
105+
case "expression" -> scriptModule.engines.get("expression").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
106+
case "metal" -> bareMetalScript();
107+
case "painless_cast" -> scriptModule.engines.get("painless")
108+
.compile(
109+
"test",
110+
"((org.elasticsearch.index.fielddata.ScriptDocValues.Longs)doc['n']).value",
111+
ScoreScript.CONTEXT,
112+
Map.of()
113+
);
114+
case "painless_def" -> scriptModule.engines.get("painless").compile("test", "doc['n'].value", ScoreScript.CONTEXT, Map.of());
115+
default -> throw new IllegalArgumentException("Don't know how to implement script [" + script + "]");
116+
};
126117
}
127118

128119
@Setup

benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -107,20 +107,12 @@ public class AggConstructionContentionBenchmark {
107107

108108
@Setup
109109
public void setup() {
110-
switch (breaker) {
111-
case "real":
112-
breakerService = new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings);
113-
break;
114-
case "preallocate":
115-
preallocateBreaker = true;
116-
breakerService = new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings);
117-
break;
118-
case "noop":
119-
breakerService = new NoneCircuitBreakerService();
120-
break;
121-
default:
122-
throw new UnsupportedOperationException();
123-
}
110+
breakerService = switch (breaker) {
111+
case "real", "preallocate" -> new HierarchyCircuitBreakerService(Settings.EMPTY, List.of(), clusterSettings);
112+
case "noop" -> new NoneCircuitBreakerService();
113+
default -> throw new UnsupportedOperationException();
114+
};
115+
preallocateBreaker = breaker.equals("preallocate");
124116
bigArrays = new BigArrays(recycler, breakerService, "request");
125117
}
126118

benchmarks/src/main/java/org/elasticsearch/benchmark/search/fetch/subphase/FetchSourcePhaseBenchmark.java

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -52,22 +52,13 @@ public class FetchSourcePhaseBenchmark {
5252

5353
@Setup
5454
public void setup() throws IOException {
55-
switch (source) {
56-
case "tiny":
57-
sourceBytes = new BytesArray("{\"message\": \"short\"}");
58-
break;
59-
case "short":
60-
sourceBytes = read300BytesExample();
61-
break;
62-
case "one_4k_field":
63-
sourceBytes = buildBigExample("huge".repeat(1024));
64-
break;
65-
case "one_4m_field":
66-
sourceBytes = buildBigExample("huge".repeat(1024 * 1024));
67-
break;
68-
default:
69-
throw new IllegalArgumentException("Unknown source [" + source + "]");
70-
}
55+
sourceBytes = switch (source) {
56+
case "tiny" -> new BytesArray("{\"message\": \"short\"}");
57+
case "short" -> read300BytesExample();
58+
case "one_4k_field" -> buildBigExample("huge".repeat(1024));
59+
case "one_4m_field" -> buildBigExample("huge".repeat(1024 * 1024));
60+
default -> throw new IllegalArgumentException("Unknown source [" + source + "]");
61+
};
7162
fetchContext = new FetchSourceContext(
7263
true,
7364
Strings.splitStringByCommaToArray(includes),

benchmarks/src/main/java/org/elasticsearch/benchmark/xcontent/FilterContentBenchmark.java

Lines changed: 25 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -64,20 +64,12 @@ public class FilterContentBenchmark {
6464

6565
@Setup
6666
public void setup() throws IOException {
67-
String sourceFile;
68-
switch (type) {
69-
case "cluster_stats":
70-
sourceFile = "monitor_cluster_stats.json";
71-
break;
72-
case "index_stats":
73-
sourceFile = "monitor_index_stats.json";
74-
break;
75-
case "node_stats":
76-
sourceFile = "monitor_node_stats.json";
77-
break;
78-
default:
79-
throw new IllegalArgumentException("Unknown type [" + type + "]");
80-
}
67+
String sourceFile = switch (type) {
68+
case "cluster_stats" -> "monitor_cluster_stats.json";
69+
case "index_stats" -> "monitor_index_stats.json";
70+
case "node_stats" -> "monitor_node_stats.json";
71+
default -> throw new IllegalArgumentException("Unknown type [" + type + "]");
72+
};
8173
source = readSource(sourceFile);
8274
filters = buildFilters();
8375
parserConfig = buildParseConfig();
@@ -87,31 +79,25 @@ private Set<String> buildFilters() {
8779
Map<String, Object> flattenMap = Maps.flatten(XContentHelper.convertToMap(source, true, XContentType.JSON).v2(), false, true);
8880
Set<String> keys = flattenMap.keySet();
8981
AtomicInteger count = new AtomicInteger();
90-
switch (fieldCount) {
91-
case "10_field":
92-
return keys.stream().filter(key -> count.getAndIncrement() % 5 == 0).limit(10).collect(Collectors.toSet());
93-
case "half_field":
94-
return keys.stream().filter(key -> count.getAndIncrement() % 2 == 0).collect(Collectors.toSet());
95-
case "all_field":
96-
return new HashSet<>(keys);
97-
case "wildcard_field":
98-
return new HashSet<>(Arrays.asList("*stats"));
99-
case "10_wildcard_field":
100-
return Set.of(
101-
"*stats.nodes*",
102-
"*stats.ind*",
103-
"*sta*.shards",
104-
"*stats*.xpack",
105-
"*stats.*.segments",
106-
"*stat*.*.data*",
107-
inclusive ? "*stats.**.request_cache" : "*stats.*.request_cache",
108-
inclusive ? "*stats.**.stat" : "*stats.*.stat",
109-
inclusive ? "*stats.**.threads" : "*stats.*.threads",
110-
"*source_node.t*"
111-
);
112-
default:
113-
throw new IllegalArgumentException("Unknown type [" + type + "]");
114-
}
82+
return switch (fieldCount) {
83+
case "10_field" -> keys.stream().filter(key -> count.getAndIncrement() % 5 == 0).limit(10).collect(Collectors.toSet());
84+
case "half_field" -> keys.stream().filter(key -> count.getAndIncrement() % 2 == 0).collect(Collectors.toSet());
85+
case "all_field" -> new HashSet<>(keys);
86+
case "wildcard_field" -> new HashSet<>(Arrays.asList("*stats"));
87+
case "10_wildcard_field" -> Set.of(
88+
"*stats.nodes*",
89+
"*stats.ind*",
90+
"*sta*.shards",
91+
"*stats*.xpack",
92+
"*stats.*.segments",
93+
"*stat*.*.data*",
94+
inclusive ? "*stats.**.request_cache" : "*stats.*.request_cache",
95+
inclusive ? "*stats.**.stat" : "*stats.*.stat",
96+
inclusive ? "*stats.**.threads" : "*stats.*.threads",
97+
"*source_node.t*"
98+
);
99+
default -> throw new IllegalArgumentException("Unknown type [" + type + "]");
100+
};
115101
}
116102

117103
@Benchmark

build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/SymbolicLinkPreservingTar.java

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,11 @@ public class SymbolicLinkPreservingTar extends Tar {
4444

4545
@Override
4646
protected CopyAction createCopyAction() {
47-
final ArchiveOutputStreamFactory compressor;
48-
switch (getCompression()) {
49-
case BZIP2:
50-
compressor = Bzip2Archiver.getCompressor();
51-
break;
52-
case GZIP:
53-
compressor = GzipArchiver.getCompressor();
54-
break;
55-
default:
56-
compressor = new SimpleCompressor();
57-
break;
58-
}
47+
final ArchiveOutputStreamFactory compressor = switch (getCompression()) {
48+
case BZIP2 -> Bzip2Archiver.getCompressor();
49+
case GZIP -> GzipArchiver.getCompressor();
50+
default -> new SimpleCompressor();
51+
};
5952
return new SymbolicLinkPreservingTarCopyAction(getArchiveFile(), compressor, isPreserveFileTimestamps());
6053
}
6154

build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -87,23 +87,17 @@ static List<String> transformConfig(List<String> lines) {
8787
}
8888

8989
switch (keyParts[2]) {
90-
case "type":
90+
case "type" -> {
9191
if (value.equals("RollingFile")) {
9292
value = "Console";
9393
}
9494
line = key + " = " + value;
95-
break;
96-
97-
case "fileName":
98-
case "filePattern":
99-
case "policies":
100-
case "strategy":
95+
}
96+
case "fileName", "filePattern", "policies", "strategy" -> {
10197
// No longer applicable. Omit it.
10298
skipNext = line.endsWith("\\");
10399
continue;
104-
105-
default:
106-
break;
100+
}
107101
}
108102
} else if (line.startsWith("rootLogger.appenderRef")) {
109103
String[] parts = line.split("\\s*=\\s*");

build-tools/src/main/java/org/elasticsearch/gradle/Architecture.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,11 @@ public enum Architecture {
2121

2222
public static Architecture current() {
2323
final String architecture = System.getProperty("os.arch", "");
24-
switch (architecture) {
25-
case "amd64":
26-
case "x86_64":
27-
return X64;
28-
case "aarch64":
29-
return AARCH64;
30-
default:
31-
throw new IllegalArgumentException("can not determine architecture from [" + architecture + "]");
32-
}
24+
return switch (architecture) {
25+
case "amd64", "x86_64" -> X64;
26+
case "aarch64" -> AARCH64;
27+
default -> throw new IllegalArgumentException("can not determine architecture from [" + architecture + "]");
28+
};
3329
}
3430

3531
}

client/benchmark/src/main/java/org/elasticsearch/client/benchmark/AbstractBenchmark.java

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,12 @@ public final void run(String[] args) throws Exception {
3636
System.exit(1);
3737
}
3838
switch (args[0]) {
39-
case "search":
40-
runSearchBenchmark(args);
41-
break;
42-
case "bulk":
43-
runBulkIndexBenchmark(args);
44-
break;
45-
default:
39+
case "search" -> runSearchBenchmark(args);
40+
case "bulk" -> runBulkIndexBenchmark(args);
41+
default -> {
4642
System.err.println("Unknown benchmark type [" + args[0] + "]");
4743
System.exit(1);
48-
44+
}
4945
}
5046

5147
}

client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkMain.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,14 @@ public class BenchmarkMain {
1616
@SuppressForbidden(reason = "system out is ok for a command line tool")
1717
public static void main(String[] args) throws Exception {
1818
String type = args[0];
19-
AbstractBenchmark<?> benchmark = null;
20-
switch (type) {
21-
case "rest":
22-
benchmark = new RestClientBenchmark();
23-
break;
24-
default:
19+
AbstractBenchmark<?> benchmark = switch (type) {
20+
case "rest" -> new RestClientBenchmark();
21+
default -> {
2522
System.err.println("Unknown client type [" + type + "]");
2623
System.exit(1);
27-
}
24+
yield null;
25+
}
26+
};
2827
benchmark.run(Arrays.copyOfRange(args, 1, args.length));
2928
}
3029
}

client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,11 @@ public String getName() {
163163
}
164164

165165
public static Status fromString(String value) {
166-
switch (value) {
167-
case "active":
168-
return Status.ACTIVE;
169-
case "paused":
170-
return Status.PAUSED;
171-
default:
172-
throw new IllegalArgumentException("unexpected status value [" + value + "]");
173-
}
166+
return switch (value) {
167+
case "active" -> Status.ACTIVE;
168+
case "paused" -> Status.PAUSED;
169+
default -> throw new IllegalArgumentException("unexpected status value [" + value + "]");
170+
};
174171
}
175172
}
176173
}

client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -149,20 +149,11 @@ private static IndexEntry parseIndexEntry(XContentParser parser) throws IOExcept
149149
parser.nextToken();
150150
if (parser.currentToken() == Token.START_OBJECT) {
151151
switch (parser.currentName()) {
152-
case "aliases":
153-
indexAliases = parseAliases(parser);
154-
break;
155-
case "mappings":
156-
indexMappings = parseMappings(parser);
157-
break;
158-
case "settings":
159-
indexSettings = Settings.fromXContent(parser);
160-
break;
161-
case "defaults":
162-
indexDefaultSettings = Settings.fromXContent(parser);
163-
break;
164-
default:
165-
parser.skipChildren();
152+
case "aliases" -> indexAliases = parseAliases(parser);
153+
case "mappings" -> indexMappings = parseMappings(parser);
154+
case "settings" -> indexSettings = Settings.fromXContent(parser);
155+
case "defaults" -> indexDefaultSettings = Settings.fromXContent(parser);
156+
default -> parser.skipChildren();
166157
}
167158
} else if (parser.currentToken() == Token.VALUE_STRING) {
168159
if (parser.currentName().equals("data_stream")) {

client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicenseStatus.java

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,11 @@ public String label() {
2727
}
2828

2929
public static LicenseStatus fromString(String value) {
30-
switch (value) {
31-
case "active":
32-
return ACTIVE;
33-
case "invalid":
34-
return INVALID;
35-
case "expired":
36-
return EXPIRED;
37-
default:
38-
throw new IllegalArgumentException("unknown license status [" + value + "]");
39-
}
30+
return switch (value) {
31+
case "active" -> ACTIVE;
32+
case "invalid" -> INVALID;
33+
case "expired" -> EXPIRED;
34+
default -> throw new IllegalArgumentException("unknown license status [" + value + "]");
35+
};
4036
}
4137
}

0 commit comments

Comments
 (0)