Skip to content

Commit

Permalink
Use Java 14 switch expressions (elastic#82178)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
arteam authored Jan 10, 2022
1 parent 35a79bc commit 0699c93
Show file tree
Hide file tree
Showing 720 changed files with 7,815 additions and 13,308 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,12 @@ public class FilterContentBenchmark {

@Setup
public void setup() throws IOException {
String sourceFile;
switch (type) {
case "cluster_stats":
sourceFile = "monitor_cluster_stats.json";
break;
case "index_stats":
sourceFile = "monitor_index_stats.json";
break;
case "node_stats":
sourceFile = "monitor_node_stats.json";
break;
default:
throw new IllegalArgumentException("Unknown type [" + type + "]");
}
String sourceFile = switch (type) {
case "cluster_stats" -> "monitor_cluster_stats.json";
case "index_stats" -> "monitor_index_stats.json";
case "node_stats" -> "monitor_node_stats.json";
default -> throw new IllegalArgumentException("Unknown type [" + type + "]");
};
source = readSource(sourceFile);
filters = buildFilters();
parserConfig = buildParseConfig();
Expand All @@ -87,31 +79,25 @@ private Set<String> buildFilters() {
Map<String, Object> flattenMap = Maps.flatten(XContentHelper.convertToMap(source, true, XContentType.JSON).v2(), false, true);
Set<String> keys = flattenMap.keySet();
AtomicInteger count = new AtomicInteger();
switch (fieldCount) {
case "10_field":
return keys.stream().filter(key -> count.getAndIncrement() % 5 == 0).limit(10).collect(Collectors.toSet());
case "half_field":
return keys.stream().filter(key -> count.getAndIncrement() % 2 == 0).collect(Collectors.toSet());
case "all_field":
return new HashSet<>(keys);
case "wildcard_field":
return new HashSet<>(Arrays.asList("*stats"));
case "10_wildcard_field":
return Set.of(
"*stats.nodes*",
"*stats.ind*",
"*sta*.shards",
"*stats*.xpack",
"*stats.*.segments",
"*stat*.*.data*",
inclusive ? "*stats.**.request_cache" : "*stats.*.request_cache",
inclusive ? "*stats.**.stat" : "*stats.*.stat",
inclusive ? "*stats.**.threads" : "*stats.*.threads",
"*source_node.t*"
);
default:
throw new IllegalArgumentException("Unknown type [" + type + "]");
}
return switch (fieldCount) {
case "10_field" -> keys.stream().filter(key -> count.getAndIncrement() % 5 == 0).limit(10).collect(Collectors.toSet());
case "half_field" -> keys.stream().filter(key -> count.getAndIncrement() % 2 == 0).collect(Collectors.toSet());
case "all_field" -> new HashSet<>(keys);
case "wildcard_field" -> new HashSet<>(Arrays.asList("*stats"));
case "10_wildcard_field" -> Set.of(
"*stats.nodes*",
"*stats.ind*",
"*sta*.shards",
"*stats*.xpack",
"*stats.*.segments",
"*stat*.*.data*",
inclusive ? "*stats.**.request_cache" : "*stats.*.request_cache",
inclusive ? "*stats.**.stat" : "*stats.*.stat",
inclusive ? "*stats.**.threads" : "*stats.*.threads",
"*source_node.t*"
);
default -> throw new IllegalArgumentException("Unknown type [" + type + "]");
};
}

@Benchmark
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,17 @@ static List<String> transformConfig(List<String> 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*");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "]");
};
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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);

}
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "]");
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "]");
};
}
}
Loading

0 comments on commit 0699c93

Please sign in to comment.